Default Parameters – ECMAScript 6

In JavaScript, parameters of functions default to undefined. However, in some situations, it might be useful to set a different default value.

In the past, the default value for a parameter is defined in the function body based on the value of the parameter as below:

function multiply(a, b) {
    b = (typeof b !== 'undefined') ? b : 1;
    return a * b;
}

console.log(multiply(5, 2)); // 10
console.log(multiply(5, 1)); // 5
console.log(multiply(5)); // 5

In the above code snippet the typeof parameter b is being checked, if the value is undefined then the value is set to 1.
Sometimes people will be using || operator to set default value as below

function multiply(a, b) {
    a = a;
    b = b || 1;
    return a * b;
}

console.log(multiply(5, 5)); // 25 -- value of b is 5
console.log(multiply(5)); // 5 -- value of b is 1, which taken from
                      // initialization using || operator

This pattern is most used but is dangerous when we pass values like

console.log(multiply(5, 0));

Because the 0 is falsy, and so the b || 1 results in 1, not the directly passed in 0. To handle this, coders started initializing value in function bodies.

In ECMAScript 6, the checks in the function body are no longer needed, we can define the default value in function head itself as follows:

function multiply(a, b = 1) {
    return a * b;
}

console.log(multiply(5, 2)); // 10 -- value of b is 2
console.log(multiply(5, 5)); // 25 -- value of b is 5
console.log(multiply(5)); // 5 -- value of b is 1, which taken from
                  // default parameter initialization

console.log(multiply(5, undefined)); // 5 -- value of b is 1,
                 // even if we pass  undefined as value to parameter b

The default value for parameter b is initialized from function head if it didn’t have any valid input.

If we convert the above ES6 code into native javascript code using Babel transpiler, we will get the following equivalent code

"use strict";

function multiply(a) {
    var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;

    return a * b;
}

console.log(multiply(5, 2)); // 10 -- value of b is 2
console.log(multiply(5, 5)); // 25 -- value of b is 5
console.log(multiply(5)); // 5 -- value of b is 1, which taken from
// default parameter initialization

console.log(multiply(5, undefined)); // 5 -- value of b is 1,
// even if we pass  undefined as value to parameter b

ECMAScript 6 is a syntactic sugar for the existing components 🙂

Happy Coding 🙂

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