Knowledgize

Array Spreading

The array spread syntax in JavaScript allows an iterable (such as an array or a string) to be expanded in places where zero or more arguments or elements are expected. It is denoted by three dots (...). This syntax can be used in various contexts, such as function calls, array literals, and object literals.



Key Features


  1. Function Calls: Expands an array into individual arguments.
  2. Array Literals: Expands elements of an iterable into an array.
  3. Object Literals: Copies properties from one object to another (note: not technically array spread, but similar syntax).


Examples


Function Calls

Using spread syntax to pass array elements as arguments to a function:


function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // Output: 6


Array Literals

Using spread syntax to create a new array by expanding elements of an existing array:


const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; console.log(arr2); // Output: [1, 2, 3, 4, 5]


Combining Arrays

Using spread syntax to combine multiple arrays:


const arr1 = [1, 2]; const arr2 = [3, 4]; const combined = [...arr1, ...arr2]; console.log(combined); // Output: [1, 2, 3, 4]


Copying Arrays

Using spread syntax to create a shallow copy of an array:


const original = [1, 2, 3]; const copy = [...original]; console.log(copy); // Output: [1, 2, 3]