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;

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

var 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];

); // [4, 4]

Passing undefined as arguments is equivalent to not passing.

// passing undefined is equivalent as not passing

function f(x=4) {
    return x;

); // returns 4

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

Function Topic

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

  1. JS: Function Object
  2. JS: Function.prototype
Like what you read? Buy JavaScript in Depth