Optional Arguments

All function arguments are optional and when omitted are given the value "undefined".


Default Values

Added in ES 2015.
Instead of always checking for undefined values the default values can be placed in the function declaration.

function methodOne( a = 10, b = 20) { 
   console.log(a + b);
}

You can even use a function to retreive a default value
The getDefaultValue will only be called when the second argument is omitted.

function getDefaultValue() { 
   return 20;
}

function methodTwo( a = 10, b = getDefaultValue() ) {
   console.log(a + b);
}

You can even perform operations in the function declaration
The default values are evaluated at call time.

function methodThree( a , b = a + a , c = b * b ) { 
   console.log(c);
}







© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext