Spread and Rest Operators – More Flexibility with ’…’
The three dots ... have gained special significance in JavaScript since ES6. With the Spread and Rest Operator, arrays and objects can be manipulated elegantly, leading to more flexible and readable code. In this article, you’ll learn how to effectively use these operators.
Spread Operator (...)
The Spread Operator allows you to expand iterables like arrays or strings, i.e., to unpack their elements individually, making code simpler and more readable.
Here are some practical use cases for the three magic dots.
Use Cases:
-
Merging Arrays:
Before ES6, arrays had to be merged using
concat:const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combined = array1.concat(array2); console.log(combined); // [1, 2, 3, 4, 5, 6]With the Spread Operator, merging becomes easier and clearer:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combined = [...array1, ...array2]; console.log(combined); // [1, 2, 3, 4, 5, 6] -
Copying Arrays:
To create a shallow copy of an array, the Spread Operator can be used:
const original = [1, 2, 3]; const copy = [...original]; copy.push(4); console.log(original); // [1, 2, 3] console.log(copy); // [1, 2, 3, 4] -
Calling Functions with Multiple Arguments:
When a function expects multiple parameters, an array can be passed with the Spread Operator:
function add(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; console.log(add(...numbers)); // 6 -
Converting Strings into Arrays:
const word = 'Hello'; const letters = [...word]; console.log(letters); // ['H', 'e', 'l', 'l', 'o'] -
Merging Objects (since ES2018):
Objects can also be merged with the Spread Operator:
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const mergedArrays = { ...obj1, ...obj2 }; console.log(mergedArrays); // { a: 1, b: 3, c: 4 }Note that with identical keys, the value of the last object is used (
b: 3overwritesb: 2).
Rest Operator (...)
The Rest Operator collects multiple elements and packs them into an array or object. It is often used in function parameters or during destructuring.
Use Cases:
-
Variable Number of Function Arguments:
Previously,
argumentswas used to access all function arguments:function sum() { let total = 0; for (let i = 0; i < arguments.length; i++) { total += arguments[i]; } return total; } console.log(sum(1, 2, 3)); // 6With the Rest Operator, the code becomes clearer:
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3)); // 6 -
Destructuring Arrays:
const [first, second, ...rest] = [10, 20, 30, 40, 50]; console.log(first); // 10 console.log(second); // 20 console.log(rest); // [30, 40, 50] -
Destructuring Objects:
const person = { name: 'Laura', age: 25, city: 'Hamburg', country: 'Germany' }; const { name, ...details } = person; console.log(name); // 'Laura' console.log(details); // { age: 25, city: 'Hamburg', country: 'Germany' }
Important Differences and Notes
-
Positioning: With the Spread Operator, elements are expanded, so it must be used where multiple values are expected (e.g., in function calls or array literals). The Rest Operator collects values and must therefore be at the end in function parameters or destructuring assignments.
// Spread in function call func(...args); // Rest in function definition function func(...args) { } -
Single Use of Rest Operator: In a function parameter list or destructuring assignment, the Rest Operator can only be used once and must take the last position.
function incorrect(...args, lastArg) { } // Error function correct(firstArg, ...args) { } // OK
Practical Examples
-
Creating Clones and Modifications of Arrays and Objects:
const originalArray = [1, 2, 3]; const newArray = [...originalArray, 4, 5]; console.log(newArray); // [1, 2, 3, 4, 5] const originalObject = { a: 1, b: 2 }; const newObject = { ...originalObject, b: 3, c: 4 }; console.log(newObject); // { a: 1, b: 3, c: 4 } -
Handling Optional Parameters:
function createUser(name, age, ...options) { return { name, age, options }; } console.log(createUser('Max', 30, 'Admin', true)); // { name: 'Max', age: 30, options: ['Admin', true] } -
Working with DOM Elements (Browser):
const divs = document.querySelectorAll('div'); const nodesArray = [...divs]; // Convert NodeList to Array nodesArray.forEach(div => { // Manipulation of Div elements });
Conclusion
The Spread and Rest Operators provide a powerful and flexible way to work with arrays, objects, and function parameters. They not only make code shorter but also more readable and easier to maintain.
Experiment with the three dots ... in your next project and discover how they can simplify your JavaScript development!