Exploring two recent features that will make your code cleaner and more robust

The Rest and Spread operators were introduced in ES6 (2015) and further extended in ES9 (2018). In this article, I will explain what these operators do and provide some practical use-cases for modernizing your code.


Rest

JavaScript’s rest parameter is a way of passing a variable number of arguments to a function in a single parameter.

The basic syntax uses three dots before the parameter name, and can be used as follows:

function f(x, ...args) {
    console.log(args instanceof Array);    // -> true
    console.log(args.length);              // -> 3
    console.log(args[0]);                  // -> 2
    console.log(args[1]);                  // -> Hello
}
f(1, 2, 'Hello', 3);

The semantics of the ... could be conceptualized as ‘the rest of the parameters’. Note that default values are not allowed for the rest parameter, so we cannot write ...args = 1,2,3.


Spread

The spread operator could be thought of as the inverse of the rest parameter.

Rather than packing multiple arguments into a single parameter, the spread operator unpacks a collection into individual values. From ES9 onwards, the spread operator works on objects, arrays, and strings and can be used as follows:

function f(...args) {
    console.log(args);        // -> [1, 2, "Hello", 3]
}

const myargs = [1, 2, 'Hello', 3];
f(...myargs);

The semantics of the ... in the spread operator could be conceptualized as ‘spread across multiple variables’. So, in the above example, the elements of the array myargs are spread across four input parameters consumed by the function f().

#programming #web-development #javascript #code #software-development #rest

Modernize Your JavaScript with Rest and Spread
1.15 GEEK