Skip to main content

Command Palette

Search for a command to run...

Spread vs Rest Operators in JavaScript

Updated
•3 min read•View as Markdown
Spread vs Rest Operators in JavaScript

What spread operator does

Spread operator is used to unpack the values from an array or object.

Analogy : Throwing the fragile glass and spreading into pieces.

What rest operator does

Rest operator is used to collect values and pack them in array or object.

Analogy : Combining those broken pieces together to make glass again.

Differences between spread and rest

If we look at the operator then it may look same, but the place where you use it decides whether it is spread or rest.

Using spread with arrays and objects

Spread with array

const nums = [10, 20, 30];

console.log(...nums);

Spread with object

const user = {
  name: "Kartik",
  age: 21
};

const updatedUser = {
  ...user,
  city: "Delhi"
};

Using rest with arrays and objects

Rest with array

const [first, ...others] = [10, 20, 30, 40];

Rest with object

const user = {
  name: "Kartik",
  age: 21,
  city: "Delhi"
};

const { name, ...rest } = user;

Practical use cases

Spread operator with arrays

  • spread while calling functions
function add(a, b, c) {
  return a + b + c;
}

const nums = [10, 20, 30];

console.log(add(...nums));
  • Merging two arrays
const arr1 = [1, 2];
const arr2 = [3, 4];

const merged = [...arr1, ...arr2];
  • creating copy of array - It will only create top level copy not the nested array. Nested arrays will be copied as reference.
const marks = [20, 30]

const marksCopy = [...marks]

Spread operator with Objects

  • updating the object
const user = {
  name: "Kartik",
  age: 21
};

const updatedUser = {
  ...user,
  age: 22
};
  • copying object - It will only make copy of the top level keys not the nested objects. Nested objects will be copied by reference.
const user = {
  name: "Kartik",
  age: 21
};

const userCopy = {...user}
  • Merging object
const user = {
  name: "Kartik",
  age: 21
};
const marks = {
    hindi : 50,
    english : 100
}
const merged = {...user, ...marks}

Rest operator with functions

when ...numbers is used as argument, then it means function is now able to accept infinite numbers of arguments.

All the arguments passed in the function will be given by function as an array of arguments.

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

sum(1, 2, 3, 4);