Sobes.tech
Junior

What is the spread operator used for in JavaScript?

sobes.tech AI

Answer from AI

The spread operator (ellipsis ...) is used for the following purposes:

  1. Expanding elements of iterable objects (arrays, strings) into function arguments:

    const numbers = [1, 2, 3];
    
    function sum(a, b, c) {
      return a + b + c;
    }
    
    const result = sum(...numbers); // 1 + 2 + 3 = 6
    
  2. Expanding elements of iterable objects (arrays, strings) into a new array:

    const array1 = [1, 2];
    const array2 = [3, 4];
    
    const combinedArray = [...array1, ...array2]; // [1, 2, 3, 4]
    
  3. Copying an array by value:

    const originalArray = [1, 2, 3];
    const copiedArray = [...originalArray]; // Creates a new array with the same elements
    
  4. Copying and merging object properties:

    const obj1 = { a: 1, b: 2 };
    const obj2 = { b: 3, c: 4 };
    
    const mergedObject = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 } - properties from obj2 overwrite those from obj1 with the same keys
    
  5. Copying an object by value (shallow):

    const originalObject = { a: 1, b: { c: 2 } };
    const copiedObject = { ...originalObject }; // The object itself is copied, but nested objects are referenced
    
  6. Expanding strings into arrays of characters:

    const str = "hello";
    
    const charArray = [...str]; // ["h", "e", "l", "l", "o"]