What is rest and spread operator in JavaScript?
The “rest” operator and the “spread” operator are two important features in JavaScript that allow you to work with arrays and objects in a more convenient and efficient way.
The “rest” operator (represented by three dots ...
) is used to gather up all remaining elements of an array or all properties of an object into a single variable. This operator is especially useful when you need to pass a varying number of arguments to a function or when you want to get all remaining elements in an array.
For example:
function sum(...numbers) {
let result = 0;
for (let num of numbers) {
result += num;
}
return result;
}
console.log(sum(1, 2, 3, 4, 5)); // 15
In this code, the “rest” operator is used to gather all arguments passed to the sum
function into an array numbers
.
The “spread” operator (also represented by three dots ...
) is used to spread an array or an object into individual elements or properties, respectively. This operator is especially useful when you need to copy an array or an object, or when you want to concatenate two arrays.
For example:
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [...a, ...b];
console.log(c); // [1, 2, 3, 4, 5, 6]
In this code, the “spread” operator is used to spread the elements of arrays a
and b
into a new array c
.
In summary, the “rest” operator and the “spread” operator are two powerful features in JavaScript that allow you to work with arrays and objects in a more convenient and efficient way. The “rest” operator is used to gather up all remaining elements of an array or all properties of an object into a single variable, while the “spread” operator is used to spread an array or an object into individual elements or properties.