CodeBlanks Logo Icon CodeBlanks

Spread and rest

Learn spread and rest parameters with the ... operator.

What is spread?

The spread operator is written with ... and 'spreads' an array or object: it opens its content item by item.

Array example: const a = [1, 2], const b = [3, 4]. Writing const combined = [...a, ...b] makes combined equal to [1, 2, 3, 4].

Object example: const copy = { ...user }. This copies all fields of user into a new object.

Rest parameter

The rest parameter is also written with ... but does the opposite: it collects the remaining arguments into a single array. It is used in function definitions.

Example: function sum(...nums). When called as sum(1, 2, 3), nums becomes [1, 2, 3]. You can pass as many arguments as you want.

So ... means rest (collects) in a function definition, and spread (opens) in a call or assignment.

Practice Merge arrays with spread

Declare two arrays: a = [1, 2] and b = [3, 4]. Use the spread operator to create a single array named combined. Then call console.log(combined).

Starter code

index.js
const a = [1, 2];
const b = [3, 4];
// create combined with spread
// log it with console.log

Sample solution

index.js
const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b];
console.log(combined);

Expected output

[ 1, 2, 3, 4 ]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Spread/rest usages

Term Meaning
[...a, ...b] Merge arrays
{ ...obj } Copy an object
...args Rest parameter
f(...arr) Spread array as arguments

2 Merge with spread

Question
const combined = [____];
Answer
const combined = [...a, ...b];

Explanation: ...a, ...b opens and merges two arrays.

3 What does the rest parameter do?

  • Collects remaining arguments into an array Correct answer
  • Copies an array
  • Takes the first argument
  • Reverses an array

Explanation: Rest collects remaining arguments into one array.

All lessons in Beginner