Door 04 | JS Adventskalender
Skip to content

Door 04

Published: at 07:00 AMSuggest Changes

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:

  1. 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]
    
  2. 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]
    
  3. 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
    
  4. Converting Strings into Arrays:

    const word = 'Hello';
    const letters = [...word];
    
    console.log(letters); // ['H', 'e', 'l', 'l', 'o']
    
  5. 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: 3 overwrites b: 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:

  1. Variable Number of Function Arguments:

    Previously, arguments was 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)); // 6
    

    With 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
    
  2. 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]
    
  3. 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

Practical Examples

  1. 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 }
    
  2. 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] }
    
  3. 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!


Previous Post
Door 05
Next Post
Door 03