[JavaScript – ES2015] Parameters

ES2015 provides new syntax of how you work with function parameters: “Default“, “Rest, and “Spread“. Let’s see what they are and how you can use them.

 

1. Default Parameters (=)

JavaScript function parameters are very flexible. The typical technique to provide the default value when the parameter is not specified is the OR (||) operator.

let doWork = function (name) {
    name = name || 'Homer';
    console.log(name);
};
doWork(); // Homer
doWork('Bart'); // Bart
doWork(null); // Homer

In ES2015, you can do it better.

let doWork = function (name = 'Homer') {
    console.log(name);
};
doWork(); // Homer
doWork('Bart'); // Bart
doWork(null); // null

Be careful with the different behavior: Default parameters only work when parameters are “undefined”.

 

2. Rest Parameters (…)

Rest parameters let you work with variable (unknown) number of parameters. Traditionally, the “arguments” object is used but with other parameters it becomes quite confusing to use.

let adder = function (weight) {
    let result = 0;
    for (let i = 1; i < arguments.length; i++) {
        result += arguments[i];
    }
    return result * weight;
};
console.log(adder(10, 1, 2, 3, 4, 5)); // 150

The new syntax makes your code a lot more elegant and easy to read. The rest parameter should be the last parameter in function because it grabs everything.

let adder = function (weight, ...numbers) {
    let result = 0;
    numbers.forEach(n => {
        result += n;
    });
    return result * weight;
};
console.log(adder(10, 1, 2, 3, 4, 5)); // 150

 

3. Spread Operator (…)

Spread operator uses the symbol just like the rest parameters. It is used to pass each element of an array as an argument to the function.

let adder = function (a, b, c) {
    console.log(a + b + c);
};
let numbers = [1, 2, 3];
adder(numbers[0], numbers[1], numbers[2]);
adder(...numbers);
adder(...[1, 2, 3]);

Another usage of the spread operator is to build an array. You can embed one array inside of another array.

let a = [1, 2];
let b = [3, 4];
let c = [...a, ...b, 5];
console.log(c); // [1, 2, 3, 4, 5]

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s