Home > Web Front-end > JS Tutorial > How Can I Assign Default Parameter Values in JavaScript Functions?

How Can I Assign Default Parameter Values in JavaScript Functions?

Linda Hamilton
Release: 2024-12-14 04:20:10
Original
393 people have browsed it

How Can I Assign Default Parameter Values in JavaScript Functions?

Assigning Default Parameter Values in JavaScript Functions

In JavaScript, it is possible to assign default values to function parameters, allowing for optional arguments. This feature was introduced in ES6/ES2015. To define a default parameter value, simply assign the desired value to the parameter in the function declaration, as seen below:

function read_file(file, delete_after = false) {
  // Code
}
Copy after login

In this case, the delete_after parameter has a default value of false. If the function is called without specifying a value for the delete_after parameter, the default value will be used. If, however, a value is passed in for this parameter, the passed-in value will override the default.

Prior to ES6

Before the introduction of default parameters in ES6, developers employed various methods to simulate this behavior. One common approach was to use the typeof operator to check if a parameter was defined and assign a default value accordingly. Here's an example:

function foo(a, b) {
  a = typeof a !== 'undefined' ? a : 42;
  b = typeof b !== 'undefined' ? b : 'default_b';
  ...
}
Copy after login

Destructuring for Default Parameters

In ES6, destructuring can also be utilized to simulate default values for named parameters. By assigning an object with default values to a parameter, you can provide optional arguments. Consider the following example:

function myFor({ start = 5, end = 1, step = -1 } = {}) { 
    // Use the variables `start`, `end` and `step` here
    ···
}

// Sample calls
myFor({ start: 3, end: 0 });
myFor(); // Without any parameters
Copy after login

In this example, if the myFor function is called without arguments, the default values for start, end, and step will be used. Alternatively, if specific values are provided for these parameters during the function call, they will override the defaults.

The above is the detailed content of How Can I Assign Default Parameter Values in JavaScript Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template