A myth story of Spread and Rest Operator.
Certainly! The spread operator (…) and the rest parameter (…) are both features introduced in ECMAScript 6 (ES6), also known as ECMAScript 2015, for handling arrays and objects in JavaScript.
According to MDN
Spread Operator:
The spread (…) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
Rest Operator:
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.
Syntax:
Now let's see the syntax for both the rest and spread operator.
Rest Operator:
function mockFunction(one, two, …args) {
console.log(…args);
}
mockFunction(1,2,3,4,5)
Rest Operator:
const array = [1, 2, 3];
const obj = { …array };
We use the same syntax (…name) for both operators. Three dots before the array name or parameter name. The Spread operator is commonly used for copying objects or arrays, while the Rest operator is used in the parameter of a function. The Rest operator picks all the arguments and passes them to the function.
Note: We can name anything for the Rest operator, but the Spread operator will use the same name of the array or object.
Result/Output:
Let's have a look at the output of both the operators.
Rest Operator:
function mockFunction(one, two, …args) {
console.log(…args);
}
mockFunction(1,2,3,4,5)
Result: 2,3,4
Rest Operator:
const array = [1, 2, 3];
console.log(…array)
Result: 1,2,3
From example, we can see that the results are the same. Both the operators pick the content from the array and arguments. Behind the scenes both are working the same, just picking the the inner content.
Note: Both Spread and Rest operator work in the same way. Naming and calling it differently is just a classification with little difference.