Skip to main content

Command Palette

Search for a command to run...

Biggest Mystery Solved: Spread vs Rest Operators

Updated
4 min read

What are we gonna Study?

Hey there folks, hope you are doing great in your day to day coding life, let's gather some new knowledge together :)

The topics for today are:

  1. What spread operator does

  2. What rest operator does

  3. Differences between spread and rest

  4. Using spread with arrays and objects

  5. Practical use cases

Gather all the focus from your crush to here and bear with me till the end, You wouldn't even realise that you learnt new things, in just sipping your tea/coffee ☕


What Spread Operator Does?

So, basically spread operator is just like its name, it spreads everything :)

Let's take some exampes of spread operator:

const original = [1, 2, 3];
const copy = [...original]; // [1, 2, 3]
  • Here, the spread operator (...) allowed us to spread all the values of the original array and then gather them in a new array.

  • Ultimately, created a new copied array that is exactly the same.

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4]
  • Here, we made a new array by spreading 2 arrays, which means it can also join arrays.
const character = { name: "Naurto", age: 16 };
const update = { age: 17, location: "Konoha" };
const updatedCharacter = { ...user, ...update };
// { name: "Naurto", age: 17, location: "Konoha" }
  • Here, we merged two objects into one using spread operator and the other object overwrite the first object's value.

  • Which means it can also override values.

const numbers = [10, 20, 30];
const result = Math.max(...numbers);
  • Yes, spread can also be done in functions like in Math.max() function we have to pass values out of which the largest one is given beck to us.

  • So, what we did is instead of adding them manually, we spread the array itself.

const str = "Dattebayo";
const chars = [...str];\
// ['D', 'a', 't', 't', 'e', 'b', 'a', 'y', 'o']
  • Notice here, we can also make array out of string using spread.

What is Rest Operator?

Like Spread operator the syntax here is exactly same, just the ellipses (...)

But just because the syntax is same, it doesn't means the work is same as well...

Let me show you the code directly, it'll help you understand that much better.

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

console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
  • Here, in this function we are passing some numbers (indefinite)

  • The rest operator here assigns all those numbers to an array...

const colors = ['red', 'green', 'blue', 'yellow', 'purple'];
const [first, second, ...remaining] = colors;

console.log(first); // 'red'
console.log(second); // 'green'
console.log(remaining); // ['blue', 'yellow', 'purple']
  • Here we are destructuring the array. (If you don't know about destructuring, Click here)

  • We assigned red to first, green to second, and then we said all the rest would get assigned to an array named remaining... Got that? I hope so...

const chraracter = {
  name: 'Yagami Light',
  superPower: 'Death Note',
  role: 'Villian'
};

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

console.log(name); // 'Yagami Light'
console.log(otherDetails);
// { superPower: 'Death Note', role: 'Villian }

This one is exactly like the same, I don't think you need explanation now :)


Spread VS Rest

Parameter Rest Spread
Work Gathers multiple items into one Unpacks one item to many
Where Used in function params, and destructuring. Used in function calls, array/object literals.

There aren't much differences are there?


Wrap Up!

You might be thinking there are 2 more sections left to dicuss right?

Actually we have already discussed them so deeply in the examples :)

So, that was it from my side guys, I'll catch you in the next blog until then keep coding and enjoy your tea/coffee too! ☕💝

JavaScript: Everything you should know

Part 22 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

The Truth About `new` Keyword in JavaScript

What are we gonna Study? Hey there folks, hope you are doing great and having fun in your dev life! So, today we'll discuss about the following topics: What the new keyword does Constructor function

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!