๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Spread

The spread syntax unpacks the items of a list into a new place. It is written as three dots before a value.

Copy an array

The copy gains a new item with push. The original array logs unchanged.

const fruits = ["Apple", "Pear"];
const copy = [...fruits];
copy.push("Plum");
console.log(copy);
console.log(fruits);

Join two arrays

Both arrays spread into one pair of brackets. The items keep their order.

const first = [1, 2];
const second = [3, 4];
const both = [...first, ...second];
console.log(both);

Spread into a call

The function total takes three separate numbers. Spread hands the array items over one by one.

function total(a, b, c) {
  return a + b + c;
}
const nums = [10, 20, 30];
console.log(total(...nums));

Example

const person = { name: "Ana", city: "Oslo" };
const moved = { ...person, city: "Bergen" };
console.log(moved);
console.log(person);

Key points

  • Spread is written as ... before an array or object.
  • Spreading an array into brackets copies its items.
  • A copy made with spread can change on its own.
  • Spread can join two arrays into one array.
  • Spread can feed array items into a function call as separate arguments.
  • Spread also copies the properties of an object.

In this example, spread copies the properties of person into a new object. The city entry after the spread replaces the copied city. The original object logs with its city unchanged.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does the code [...nums] create when nums is an array?