JS: Function Argument Default Value
New in JS2015.
Function Argument Default Value
Function's parameters can specify default values, like this:
function f (param=value) {body}
// function with default parameter values function f(x = 4, y = 2) { return [x, y]; } console.log(f()); // [ 4, 2 ]
Default Value Expression Evaluated at Call Time
Default value expression are evaluated at call time. For example,
function f(x=m) { return x; }
the m
is evaluated when f
is called.
// function, param default value expression is eval'd at call time let m = 2; function f(x=m) { return x; } m = 3; console.log( f() === 3 ); // true
Later Value Expression Have Access to Previous Value Expression
Later value expression have access to previous value expression.
// function with default value for parameter // later expression can refer previous function f(x=4, y=x) { return [x , y]; } console.log( f() ); // [4, 4]
Passing undefined as Argument
Passing undefined
as arguments is equivalent to not passing.
// passing undefined is equivalent as not passing function f(x=4) { return x; } console.log( f(undefined) === 4 ); // true
Passing null as Argument
Passing null
has no special effect. The argument just got the value of null
.
function f (x=3) { return x; } console.log( f(null) === null ); // true
JavaScript, Function
- JS: Define Function
- JS: Arrow Function
- JS: Function Parameters
- JS: arguments Object
- JS: Function Rest Parameters
- JS: Function Argument Default Value
- JS: Function Argument Destructure
- JS: Function Declaration vs Function Expression
- JS: Closure
- JS: Function Call, Apply, Bind
- JS: Functional Programing
- JS: Function Pipe π
- JS: Function Object
- JS: Function Constructor
- JS: Function.prototype