JS: Function Argument Default Value

By Xah Lee. Date: . Last updated: .

New in ES2015.

Function's parameters can specify default values.

// function with default parameter values
function f(x=4, y=2) {
    return x + y;
}

console.log(
    f()
); // 6

Before ES2015, you have to use the magical arguments object, by testing if a arg has value of undefined then set value.

[see JS: Function's “arguments” Object]

Default value expression are evaluated at call time.

// 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

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 arguments is equivalent to not passing.

// passing undefined is equivalent as not passing

function f(x=4) {
    return x;
}

console.log(
    f(undefined)
); // returns 4

ECMAScript 2015 §Ordinary and Exotic Objects Behaviours#sec-ecmascript-function-objects

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth