Skip to main content

Command Palette

Search for a command to run...

Spread vs Rest Operators in JavaScript

Updated
7 min read
Spread vs Rest Operators in JavaScript

What is the Spread Operator

The spread operator is a convenient syntax in JavaScript that expands values from an array or an object into individual elements.

Think of it like opening a packed box and spreading all the items out on a table. You are taking something that is grouped together and unpacking it so you can see or use every individual piece.

const numbers = [1, 2, 3]; 
const newNumbers = [...numbers];

What happens if we try this? Here is the step-by-step breakdown

  1. We define an array called numbers containing three items.

  2. We create a second array called newNumbers.

  3. Inside the new array, we use three dots ... followed by the numbers variable.

  4. JavaScript looks inside numbers, unpacks the values 1, 2, 3, and places them individually into newNumbers.

Spread with Arrays

What problem does this solve? Often, you need to combine two existing arrays into a brand new one without mutating the originals. The spread operator makes this incredibly simple.

Imagine having two separate stacks of cards. You take the first stack, fan it out on the table, and then take the second stack and fan it out right next to the first one, creating one continuous line.

const arr1 = [1, 2]; 
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];

Here is exactly what JavaScript is doing

  1. It creates an empty array for combined.

  2. It sees ...arr1 and pours its contents 1, 2 into the new array.

  3. It sees ...arr2 and pours its contents 3, 4 right after.

  4. The result is a single, flat array [1, 2, 3, 4].

Spread with Objects

The spread operator is equally useful for objects. It allows you to copy properties from one object into another, and even add new properties along the way.

Think of it like photocopying a recipe card. You copy all the original instructions perfectly, but you write down your own extra ingredient at the bottom of the new copy.

const user = { 
name: "Rahul" 
}; 
const updatedUser = { ...user, age: 22 };

Let us walk through this step-by-step

  1. We have an initial user object with a name property.

  2. We create a new object called updatedUser.

  3. The ...user syntax unpacks all existing properties from user (just name: "Rahul") and places them into the new object.

  4. We then add a new property, age: 22, alongside the copied data.

What is the Rest Operator

The rest operator looks exactly the same as spread (three dots ...), but it does the exact opposite. Instead of expanding values, the rest operator collects multiple independent values and bundles them into a single array or object.

Imagine finding a bunch of loose items scattered around your room. You grab a single bag and collect all those loose items into it so they are grouped together in one place.

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

Here is what happens step-by-step

  1. We define a function called sum and use ...numbers as the parameter.

  2. When we call this function with multiple arguments, like sum(5, 10, 15).

  3. The rest operator catches all those loose arguments.

  4. It packs them neatly into a single array [5, 10, 15] assigned to the numbers variable.

Rest in Destructuring

You will frequently see the rest operator used alongside destructuring to grab whatever items are "left over" after you take the specific ones you want.

Think about ordering a pizza. You take the first slice for yourself, and you leave the "rest" of the slices in the box for your friends.

const [first, ...rest] = [1, 2, 3, 4];

Let us break this down step-by-step

  1. We destructure an array containing four numbers.

  2. The variable first targets the very first item, which is 1.

  3. The ...rest syntax sweeps up all remaining items that were not explicitly picked.

  4. The rest variable becomes an array containing [2, 3, 4].

Spread vs Rest (Core Difference)

The core difference comes down to intent and placement. Spread expands values out. Rest collects values in.

Here is a quick text-based comparison to keep your mental model clear

Feature

Syntax

Behavior

Where it is used

Spread

...

Expands a group into single items

Array literals, object literals, function calls

Rest

...

Collects single items into a group

Function parameters, destructuring assignments

Practical Understanding

Real-World Use Cases

In modern JavaScript development, you will use these operators constantly for a few specific tasks:

  • Copying arrays: Creating safe duplicates of data so you do not accidentally modify the original.

  • Merging data: Combining multiple API responses or configuration objects into one.

  • Handling function arguments: Creating functions that can accept any number of inputs gracefully.

  • Updating objects: Updating specific fields in an object while keeping the rest of the data intact.

Practical Example

Let us look at a common scenario in an e-commerce application: adding a new price to a shopping cart.

Like adding a new purchase to a shopping receipt, you want to keep the record of the old items while officially logging the new one.

const cart = [100, 200];
const updatedCart = [...cart, 300];

Here is the step-by-step execution

  1. We start with a cart array holding two previous amounts.

  2. Instead of using .push() which mutates the original array, we create a fresh updatedCart.

  3. We spread the existing cart values (100, 200) into the new array.

  4. We add the new item 300 at the end, resulting in [100, 200, 300].

Common Mistakes

When you are learning these operators, it is easy to trip up. Keep an eye out for these common errors.

Mistake 1: Confusing spread and rest Because they both use ..., beginners often call everything the "spread operator". Remember context matters. If it is in a function definition or on the left side of an equals sign, it is rest. If it is building an array/object or passing arguments, it is spread.

Mistake 2: Using rest in the wrong position The rest operator must always be the very last item in your list. If you try to write const [...rest, last] = [1, 2, 3], JavaScript will throw an error because it does not know when to stop collecting values for rest.

Mistake 3: Thinking they behave exactly the same One unpacks, and the other packs. If you try to use spread where rest is expected, your code will either fail or behave unpredictably. Always ask yourself: "Am I trying to break this apart, or bundle it together?"

Summary

  • Spread expands values from an array or object into individual pieces.

  • Rest collects multiple individual values into a single grouped array or object.

  • Both use the ... syntax but behave differently depending on where they are written.

  • They are incredibly useful for safely copying arrays, updating objects, and writing flexible functions.

In the next article, we will explore how to flatten nested arrays in JavaScript and why it is an important concept for handling real-world data.

More from this blog