DEV Community

Hiral
Hiral

Posted on

Spread vs Rest Operators in JavaScript

JavaScript gives us powerful tools to work with data more easily—and two of the most useful are the spread (...) and rest (...) operators.

Even though they look the same, they behave very differently depending on where you use them. Let’s break it down step by step.

What the Spread Operator Does
The spread operator is used to expand (spread out) values.
Think of it like unpacking items from a box.
Example with Arrays

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

console.log(newNumbers);
// [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

Here, ...numbers takes each element and expands it into the new array.

What the Rest Operator Does

The rest operator does the opposite—it collects multiple values into one.
Think of it like packing items into a box.

function sum(...nums) {
  return nums.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4));
// 10
Enter fullscreen mode Exit fullscreen mode

...nums collects all arguments into a single array.
Using Spread with Arrays and Objects
Array

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

const combined = [...arr1, ...arr2];

console.log(combined);
// [1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

Objects:

const user = { name: "Alice", age: 25 };

const updatedUser = {
  ...user,
  age: 26
};

console.log(updatedUser);
// { name: "Alice", age: 26 }
Enter fullscreen mode Exit fullscreen mode

Spread is commonly used to copy and update data without modifying the original.

Use Cases:

  1. Copying Arrays (Without Mutation)
const original = [1, 2, 3];
const copy = [...original];
Enter fullscreen mode Exit fullscreen mode
  1. Merging Objects
const defaults = { theme: "light" };
const settings = { theme: "dark", fontSize: 16 };

const finalSettings = { ...defaults, ...settings };
Enter fullscreen mode Exit fullscreen mode
  1. Passing Arguments to Functions
const nums = [5, 10, 15];

Math.max(...nums); // 15
Enter fullscreen mode Exit fullscreen mode
  1. Extracting Values with Rest
const [first, ...others] = [10, 20, 30, 40];

console.log(first);  // 10
console.log(others); // [20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)