4 min read
•Question 11 of 50easyWhat are Spread and Rest operators?
Understanding ... operator in JavaScript.
What You'll Learn
- Spread operator usage
- Rest parameter usage
- Common patterns
Spread Operator (...)
Expands iterable elements.
code.jsJavaScript
// Array spread
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Clone array
const clone = [...arr1];
// Object spread
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// Merge objects
const merged = { ...obj1, ...obj2 };
// Function arguments
const nums = [1, 2, 3];
Math.max(...nums); // 3Rest Parameter (...)
Collects multiple elements into an array.
code.jsJavaScript
// Function rest parameter
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
// Destructuring with rest
const [first, ...rest] = [1, 2, 3, 4];
console.log(rest); // [2, 3, 4]
const { a, ...remaining } = { a: 1, b: 2, c: 3 };
console.log(remaining); // { b: 2, c: 3 }