Mastering Spread and Rest Operators: A Comprehensive Guide to Their Differences in JavaScript"
Table of contents
One of the most often asked topics in Javascript interviews is about the spread and rest operators, which may appear to be identical and interchangeable concepts. Both the rest and spread operators in JavaScript are represented by three dots (...). These two operators, however, are not the same. JavaScript introduces the rest and spread operators, which are used to handle arrays and objects in different ways. Let us examine the distinction between them:
Spread Operator:
The spread operator is used to break down the values of an array or an iterable object into individual elements. Example:
const arr1 = [1,2,3,4,5,6];
const arr2 = {...arr1}
const arr3 = [...arr1]
console.log(arr2) //{'0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6} ~ Object
console.log(arr3) //[ 1, 2, 3, 4, 5, 6 ] ~ Array
This concept aids in the destructuring of arrays into useful elements, making it easier to work with object or array entities. Perhaps some of the important spread operations are as follows:
const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr4 = [...arr1, ...arr2] //arr4 = [1, 2, 3, 4, 5, 6]
// Destructuring through spread operator:
const arr = [1,2,3,4]
const [a, b,...c] = [3,4,5,...arr]
console.log(`a: ${a}, b: ${b}, c: ${c}`)
// output- a: 3, b: 4, c: 5,1,2,3,4
When using the spread syntax (...
) in JavaScript to copy an array, it creates a new array and copies the elements from the original array into the new one. However, the spread syntax only goes one level deep while copying the array.
const originalArray = [[1, 2], [3, 4], [5, 6]];
const copiedArray = [...originalArray];
In the above code, originalArray
is a multidimensional array consisting of three sub-arrays. By using the spread syntax, we attempt to copy the originalArray
into copiedArray
.
However, it's important to note that the spread syntax only performs a shallow copy. This means that while the outer array is copied, the inner arrays are still references to the original arrays. As a result, any modifications made to the elements within the inner arrays will affect both the original and copied arrays. Like,
copiedArray[0][0] = 99;
console.log(originalArray); // Output: [[99, 2], [3, 4], [5, 6]]
In the above code, modifying copiedArray[0][0]
also changes the corresponding element in originalArray
. This is because the inner arrays are still references to the original arrays, and the spread syntax does not create deep copies of the nested arrays.
Rest Operators-
In JavaScript, the rest operator, indicated by(...
), allows you to represent an endless amount of parameters as an array. It collects the remaining parameters supplied to a method and stores them in a single array, making it easier to work with them. Example:
let sum = (...arr) => {
return a = arr.reduce((accumulator, element)=>{
return accumulator += element;
});
}
console.log(sum(1,2,3,4,5)); // output- 15
In the above code, the ` sum `
function uses the rest operator ...arr
in its parameter declaration. This indicates that the function can take any number of arguments, which are stored in an array ('arr' in the above case).
When you want to write functions that can handle a variable number of arguments without explicitly mentioning them in the function specification, the rest operator comes in handy. It allows you to operate with the arguments as an array-like structure within the function body, giving you more flexibility. It's vital to note that the rest operator can only be used as the function's final parameter. After all of the declared parameters have been assigned values, it collects the remaining inputs.
function restOperators(...arr, value) {} // this will throw an error as the rest operator must be the last/final parameter in the function prototype
// Correct form of the above declatation will be:
function restOperators(value, ...arr) {}