What does the spread operator (...) do in JavaScript?

0137

The spread operator (...) in JavaScript is used to expand or spread elements of an iterable (like an array or a string) into individual elements. It can be used in various contexts, such as:

  1. Array Literals: To create a new array by combining existing arrays or adding new elements.

    const array1 = [1, 2, 3];
    const array2 = [4, 5, 6];
    const combinedArray = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6]
  2. Function Arguments: To pass elements of an array as individual arguments to a function.

    const numbers = [1, 2, 3];
    const sum = (a, b, c) => a + b + c;
    console.log(sum(...numbers)); // 6
  3. Object Literals: To create a new object by copying properties from an existing object.

    const obj1 = { a: 1, b: 2 };
    const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
  4. String Expansion: To convert a string into an array of characters.

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

The spread operator is a powerful feature that simplifies code and enhances readability.

0 Comments

no data
Be the first to share your comment!