JS: Function Argument Default Value

By Xah Lee. Date: . Last updated: .

New in ES2015.

Function's parameters can have default value, like this:

function f(param=value) {…}

// function with default parameter values
function f(x=4, y=2) {
    console.log ( x,y );
}

f() ; // 4 2

Default Argument Before ES2015

For pre-ES2015, to define default values for optional parameter, you can just check if a argument is undefined, then set value.

// pre-ES2015. define function with optional parameter and default value

function f (x) {
    if ( x === undefined ) {
        x = 3; // default value
    }
    console.log ( x );
}

f(); // 3

Or, use the “arguments” Object.

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

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

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

Passing undefined as arguments is equivalent to not passing.

// passing undefined is equivalent as not passing

function f(x=4) {
    console.log ( x );
}

f(undefined); // 4

Passing null

Passing null does not work.

function f (x=3) { console.log ( x ); }

f(null); // null

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

Function Topic

  1. Define Function
  2. Functional Programing
  3. Arrow Function
  4. Function Parameters
  5. f Declaration vs Expression
  6. Closure
  7. Function Call, Apply, Bind
  8. Function Argument Default Value
  9. Function Rest Parameters
  10. Function Argument Destructure
  11. Function Object
  12. Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc