Skip to main content

Command Palette

Search for a command to run...

Spread vs Rest Operators in JavaScript

Published
3 min read
Spread vs Rest Operators in JavaScript

In JavaScript, you might have seen these three dots ...

Sometimes they behave like magic.

Same syntax, but different use.

Sometimes it spreads values Sometimes it collects values

So what’s actually happening?

In this blog I will share how I understand spread and rest operators and how to use them properly.


What is spread operator

Spread means:

take something and expand it

Example:

const arr = [1, 2, 3]

console.log(...arr)

Output:

1 2 3

array got expanded


Spread with arrays

const arr1 = [1, 2]
const arr2 = [3, 4]

const newArr = [...arr1, ...arr2]

Result:

[1, 2, 3, 4]

combining arrays becomes easy


Spread with objects

const user = { name: "Dhiraj" }
const updatedUser = { ...user, age: 20 }

copies old object + adds new data


Spread idea

Diagram idea:

[1, 2, 3] → 1, 2, 3

(expanding values)


What is rest operator

Rest means:

collect multiple values into one

Example:

function sum(...nums) {
  console.log(nums)
}

sum(1, 2, 3)

Output:

[1, 2, 3]

values collected into array


Rest in arrays

const arr = [1, 2, 3, 4]

const [first, ...rest] = arr

So:

  • first = 1

  • rest = [2, 3, 4]


Rest idea

Diagram idea:

1, 2, 3, 4 → [1, ...rest]

(rest collects remaining)


Spread vs Rest (main difference)

Both use ... but:

Spread:

expands values

Rest:

collects values

Simple way:

Spread = open

Rest = gather


When to use spread

Use spread when:

  • combining arrays

  • copying objects

  • adding values

Example:

const arr = [1, 2]
const newArr = [...arr, 3]

When to use rest

Use rest when:

  • function arguments

  • extracting remaining values

  • handling unknown number of inputs

Example:

function log(first, ...others) {
  console.log(first)
  console.log(others)
}

Real world feeling

Spread:

breaking things apart

Rest:

grouping things together


Small practical example

const user = {
  name: "Dhiraj",
  age: 20,
  city: "Kolkata"
}

const { name, ...rest } = user

name separate, rest contains remaining data


Spread and rest look same but do opposite things.

Spread expands

Rest collects