CodeBlanks Logo Icon CodeBlanks

Spread operator (arrays)

JavaScript course · Advanced · Lesson 30/100

Learn to spread an array's elements with ....

The spread operator

The spread operator is written with three dots: .... When you put it in front of an array, it expands its elements one by one. Writing const copy = [...fruits] copies every element of fruits into a new array; the original is not changed.

This is the same as fruits.slice(), only shorter and clearer. Because spread opens a array into a new array literal, it is widely used for merging and copying.

Combining arrays

A common use of spread is combining arrays. Put ... in front of two arrays inside a new array literal, and their elements come together as a flat list.

For example, const menu = [...morning, ...afternoon] makes menu hold every element of both arrays in a single array. This reads more clearly than morning.concat(afternoon).

Exercise Merge the task list

Create two arrays called weekend and weekdays. Fill each with at least two task strings. Then create a new array called allTasks and merge the two arrays with spread. Log allTasks with console.log.

Show example solution
const weekend = ["rest", "walk"];
const weekdays = ["coding", "meeting", "testing"];
const allTasks = [...weekend, ...weekdays];
console.log(allTasks);

Test yourself

  1. What does `const copy = [...fruits]` do?

    const fruits = ["apple", "pear"];
    const copy = [...fruits];
    • It empties the `fruits` array
    • It copies the elements of `fruits` into a new array
    • It returns the number of elements in `fruits`
    • It sorts `fruits` alphabetically
    Show answer

    It copies the elements of `fruits` into a new array — Correct. Spread expands the elements into a new array; the original is untouched.

  2. Combine two arrays

    const morning = ["tea", "coffee"];
    const afternoon = ["soup", "salad"];
    const menu = [____];
    console.log(menu);
    Show answer
    const morning = ["tea", "coffee"];
    const afternoon = ["soup", "salad"];
    const menu = [...morning, ...afternoon];
    console.log(menu);
  3. What does `[...a, ...b]` produce?

    const a = [1, 2];
    const b = [3, 4];
    const c = [...a, ...b];
    • A single array with all elements of `a` and `b`
    • A nested two-dimensional array containing `a` and `b`
    • An array with only the elements of `a`
    • An array with only the elements of `b`
    Show answer

    A single array with all elements of `a` and `b` — Correct. Spread expands both arrays; the result is a flat array.

All lessons in Advanced