The ... spread operator
When it is used with an array, it "unfolds" that array, that is, it lays out its elements in place.
Example:
javascript
const arr = [1, 2, 3];
console.log(...arr); // 1 2 3...arr unpacks the array, turning it into a sequence of values.
Without it you would get [1, 2, 3],
but with it, just 1 2 3.
Main uses with arrays:
1. Copying an array
javascript
const numbers = [1, 2, 3];
const copy = [...numbers];
console.log(copy); // [1, 2, 3]
console.log(copy === numbers); // false (a new array)This creates a shallow copy of the array.
2. Merging arrays
javascript
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
console.log(merged); // [1, 2, 3, 4]You can also insert between other elements:
javascript
const result = [0, ...a, 99, ...b];
console.log(result); // [0, 1, 2, 99, 3, 4]3. Adding elements to the start or end
javascript
const arr = [2, 3];
const newArr = [1, ...arr, 4];
console.log(newArr); // [1, 2, 3, 4]4. Passing elements as separate arguments
javascript
const nums = [10, 20, 30];
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(...nums)); // 60...nums unfolds the array into the function's arguments.
5. Creating a new array with a changed element (immutably)
javascript
const arr = [1, 2, 3];
const newArr = [...arr.slice(0, 1), 99, ...arr.slice(2)];
console.log(newArr); // [1, 99, 3]A great technique for React and other places where you can't mutate data.
6. Converting iterables into an array
javascript
const str = "hello";
const chars = [...str];
console.log(chars); // ["h", "e", "l", "l", "o"]Spread works with any iterable - strings, Set, Map, NodeList, and so on.
Important to remember:
- It makes only a shallow copy (nested objects are copied by reference).
- It only works with iterables (for example, not with plain objects, unless you use
{...obj}).
In short:
| What it does | Unfolds (unpacks) the array's elements |
|---|---|
| Type of operation | "Expansion" |
| Returns | A set of values |
| Changes the original array | No |
| Good for | copying, merging, passing arguments |
| Example | [...arr] -> [1, 2, 3] |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.