Skip to main content

Command Palette

Search for a command to run...

Understanding Spread and Rest Operators in JavaScript

Updated
•2 min read•View as Markdown

In JavaScript, you’ll often see three dots ....

At first, it looks confusing, but it actually does two simple things depending on where it is used.

  • Spread → expands values

  • Rest → collects values

Same syntax, different purpose.


What Spread Operator Does

The spread operator expands elements.

Think of it as taking something grouped and spreading it out.

Example with array:

let arr = [1, 2, 3]

let newArr = [...arr]

console.log(newArr)

Here:

  • values are copied and expanded into a new array
https://images.openai.com/static-rsc-4/GwOlrrszDTF7kdUacglKRn4x-x4kEZoGv3TGTn0dCgneXMOpoNcP3xJ1pll842idShDJLKs3XDAC-xmU2YrOL6DyEvpTQvei7CipMF65RzNM-uhOh277rJifExrKr-9K36ywbWcIgaNv7g9CYBMiHYhUBGv0kE4MkFiavLcdLvRGjygoCntixMnTJgNa9OV_?purpose=fullsize

Using Spread with Arrays

You can also combine arrays easily:

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

let combined = [...arr1, ...arr2]

console.log(combined)

Result:

[1, 2, 3, 4]

Using Spread with Objects

Spread also works with objects:

let user = { name: "Ishan" }

let updatedUser = { ...user, age: 21 }

console.log(updatedUser)

This is useful for:

  • copying objects

  • updating values


What Rest Operator Does

The rest operator collects values into a group.

Example:

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

sum(1, 2, 3, 4)

Here:

  • all values are collected into numbers array
https://images.openai.com/static-rsc-4/YnZgmJ04y74miL7g5_nRIEb24ZQZHlyzkeALuP19W6FF68fWBuIMn5_06-B8ElovLUkrqYIxbFRhwYUtf5VGXb4zt7kl64nwBFA2fTFdSNwL_kwjn0kS90oeS_XVqHOpyMC7i7PWdbnO5klWDNjliieWlShN2naBX7ugi1e63jX3_QTljOnqspm6wQoHz3oe?purpose=fullsize

Spread vs Rest (Key Difference)

This is where most people get confused.

  • Spread → expands values

  • Rest → collects values

Example:

let arr = [1, 2, 3]

function print(a, b, c) {
  console.log(a, b, c)
}

print(...arr) // spread
function print(...values) {
  console.log(values)
}

print(1, 2, 3) // rest

Practical Use Cases

Spread:

  • copying arrays

  • merging arrays

  • copying objects

Rest:

  • handling multiple arguments

  • grouping remaining values

Example:

let numbers = [1, 2, 3]

let copy = [...numbers]
function logAll(...items) {
  console.log(items)
}

One Simple Way to Think

Spread → break things apart

Rest → gather things together


Conclusion

The spread and rest operators look the same, but their behavior depends on how they are used.

Once you understand:

  • spread = expand

  • rest = collect

most confusion disappears.