The rest and spread operators are powerful features that allow you to work with arrays and function parameters more flexibly and concisely.
The explanations are as follows.
Rest Operator(...)
1. Collecting elements into an array
The rest operator allows you to collect the remaining elements of an array into a new array.
Example
const fruits = ['grape', 'banana', 'orange', 'mango'];
const [first, ...rest] = fruits;
console.log(first);
console.log(rest);
Output
2. Function parameters
The rest operator can also be used in function parameters to collect any number of arguments into an array.
Example
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4));
Output
Spread Operator (...)
1. Spreading elements
The spread operator allows you to spread the elements of an array or the properties of an object.
Example
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
console.log(combinedArray);
Output
2. Cloning arrays
You can use the spread operator to create a shallow copy of an array.
Example
const originalArray = [1, 2, 3];
const copyArray = [...originalArray];
console.log(copyArray);
console.log(originalArray === copyArray);
Output
3. Spreading object properties
Similarly, you can spread the properties of an object into a new object.
Example
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObject = { ...obj1, ...obj2 };
console.log(combinedObject);
Output
The rest and spread operators provide concise and flexible ways to work with arrays and function parameters in JavaScript which are widely used in modern JavaScript development.