In this tutorial, we will learn about JavaScript spread and rest operator with the help of detailed examples
The spread operator in JavaScript 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. It is represented by three dots (...).
Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element.
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]
You can also use the spread operator to spread the elements of an array into a function call:
let arr = [1, 2, 3];
console.log(Math.max(...arr)); // 3
let [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
The rest operator is similar to the spread operator, but it is used to capture the remaining elements of an array. It is represented by three dots (...) and is usually used in conjunction with destructuring assignment.
For example, you can use the rest operator to capture the remaining elements of an array into a new one:
let [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
You can also use the rest operator to capture the remaining elements of an array into a function argument:
function print(first, second, ...rest) {
console.log(first);
console.log(second);
console.log(rest);
}
print(1, 2, 3, 4, 5); //1
2
[3,4,5]
further usage of spread operator with function:
const add = function (...numbers) {
let sum = 0;
for( let i = 0; i < numbers.length; i++ ) sum += numbers[i];
console.log(sum);
};
add()3,2,5)
add(3, 4, 1, 4, 6, 7, 5, 2)
add(9, 2, 1, 4)
Hope you have a better understanding of the spread and rest operator after this explanation.
Top comments (0)