ES2015 (Es6) Default Parameters Syntax

Example: https://jsfiddle.net/pkygohf3/

ES2015 provides a good way to define default parameters in functions.


function example( x = 2 ) {
 console.log(x);
}
example(5);
// 5
example();
// 2

In this example, if the argument of ‘x’ is not passed to the function, it falls back to the default value of ‘2’.


function objExample1( x ) {
 console.log(x.length);
}
function objExample2( x = [] ) {
 console.log(x.length);
}
objExample1();
// Cannot read property 'length' of undefined
objExample1(['test']);
// 1
objExample2();
// 0
objExample2(['test']);
// 1

You can see here that the built in Array.length() function is failing in objExample1 as it trying to call it on ‘undefined’ argument. objExample2 fixes this by using the ES2015 default syntax as the function parameter.

This is more powerful with default objects:


const $initSetup = {
width: 400,
height: 200,
background: 'blue'
}

function defaultTest({
width = $initSetup.width,
height = $initSetup.height,
background = $initSetup.background
} = $initSetup) {

console.log(`'${width} x ${height}' with background: ${background}.`);

};

let $userSetup = {
width: 250,
background: 'red'
}

defaultTest();
//'400 x 200' with background: blue.
defaultTest($userSetup);
//'250 x 200' with background: red.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s