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

JS Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

Like it? Help me by telling your friends. Or, 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 in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog