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

  1. JavaScript: Function Object
  2. JavaScript: Function.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.