Menu
Coddy logo textTech

Spread Syntax in Arrays

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 48 of 65.

The spread syntax (...) allows an iterable, such as an array, to be expanded in places where zero or more arguments or elements are expected. It provides a concise way to perform operations like combining arrays or copying arrays.

Here are some common use cases:

1. Combining arrays:

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

2. Creating a shallow copy of an array:

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

3. Adding elements to an array:

const numbers = [1, 2, 3];
const moreNumbers = [0, ...numbers, 4];
console.log(moreNumbers); // [0, 1, 2, 3, 4]

4. Passing array elements as function arguments:

function sum(a, b, c) {
  return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
challenge icon

Challenge

Easy

Create a function called mergeArr that takes two arrays of numbers as arguments. The function should:

  1. Merge the two arrays using the spread operator
  2. Remove any duplicate numbers
  3. Return the resulting array

Cheat sheet

The spread syntax (...) allows an iterable to be expanded in places where zero or more arguments or elements are expected.

Combining arrays:

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

Creating a shallow copy:

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

Adding elements to an array:

const numbers = [1, 2, 3];
const moreNumbers = [0, ...numbers, 4];
console.log(moreNumbers); // [0, 1, 2, 3, 4]

Passing array elements as function arguments:

function sum(a, b, c) {
  return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

Try it yourself

function mergeArr(arr1, arr2) {
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow