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 }
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'; ... }
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
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!