Spread and Rest Operators Explained
Key Concepts
- Spread Operator
- Rest Operator
Spread Operator
The spread operator (...
) allows an iterable (like 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 useful for combining arrays, copying arrays, and passing multiple elements to functions.
Example:
let arr1 = [1, 2, 3]; let arr2 = [...arr1, 4, 5]; console.log(arr2); // Outputs: [1, 2, 3, 4, 5] function sum(a, b, c) { return a + b + c; } let numbers = [1, 2, 3]; console.log(sum(...numbers)); // Outputs: 6
Analogies: Think of the spread operator as spreading out a deck of cards, where each card represents an element in the array.
Rest Operator
The rest operator (...
) is used in function parameter lists to collect all remaining arguments into an array. It is particularly useful when you want to handle a variable number of arguments in a function.
Example:
function sum(...args) { return args.reduce((a, b) => a + b, 0); } console.log(sum(1, 2, 3, 4)); // Outputs: 10 function multiply(multiplier, ...theArgs) { return theArgs.map(element => multiplier * element); } console.log(multiply(2, 1, 2, 3)); // Outputs: [2, 4, 6]
Analogies: The rest operator is like collecting a hand of cards, where each card represents an argument passed to the function.