DEV Community

Cover image for Spread vs Rest Operators in JavaScript
Anoop Rajoriya
Anoop Rajoriya

Posted on

Spread vs Rest Operators in JavaScript

Spread and Rest both operators are used same three dots (...) But the difference is how it work? the are opposite in working to each other. Spread is expend the collections and in other hand rest collect those items. In this article we learn about both, what its syntax and how you can use it with arrya or object. Seeing some real world usecases.


What spread operator does

Spread operator is used to getting out all items form existing collections like arrays or objects. Its always used right side of the assignment operator (variable = ...something) and many times you seeing its use with function call (fn(...something)) pass all items to function infividually.

Think it like you passing entire container of items to some one and in the middle a guy picking all items one by one and giveing it to intended person.

What rest operator does

Rest operator collect each individual item and wrap it into container which will passing to you. You seeing it's use with functions declaration as a parameter (fn(...params){}) which collect all arguments passing to function and give a single parameter containing all those items.

Think it like you adding items in cart on amazon but you recieve a single parcel containing all you items. In the middle the amazon workers wrap you items into singel box so you only recieve one box rather than multiple boxes.

Differences between spread and rest

The only differences between them is direction of the data flow. Spread operator results data as individual pieces but rest operator result a single unit contain all items.

Features Spread Operator Rest Operator
Purpose gettin out items form container putting items within container
Syntax with collections ([1, ...nums, 2]) and function calls (Math.max(...nums)) only within function declarations (function sum(...nums){})
Results individual items form given collection single collection contains every items

Using spread with arrays and objects

With help of spread operator you can join multiple arrays into one or can add other values to it. Can create copy of the objects with some external configurations like adding some properties with defaults. Using this copy is good way for manipulating objects rather than directly assignments because it copy reference but spread operator copy objects by values.

const postiveNums = [1,2,3,4]
const negativeNums = [-1, -2, -3, -4]
const user = {
    name: "anoop",
    salary: "50k",
}

// Merging + with 0
console.log([...negativeNums, 0, ...postiveNums])
// [-1, -2, -3, -4, 0, 1, 2, 3, 4,]

// Copy by value
const copy = {...user}
copy.salary("80k")
console.log(user) // salary: "50k"
console.log(copy) // salary: "80k"
Enter fullscreen mode Exit fullscreen mode

Practical use cases

Creating Copy

You can create shalow copy with spread operator which copy values in one level depth which is safe way for data manipulation in object and arrays becuas it not mutate original one.

const user = {name: "anoop", isActive: true, salary: "50k"}
const temp = {...user}

temp.name = "dipesh"
temp.salary = "25k"

console.log(temp)
// {name: "dipesh", isActive: true, salary: "25k"}
console.log(user)
// {name: "anoop", isActive: true, salary: "50k"}
// Not mutate original one
Enter fullscreen mode Exit fullscreen mode

Merging Values

For creating new object or array with properties of another one can be done with the help of it spread operator. Also can add some other properties if you want.

const defaultSettings = {
    theme: "dark",
    font: 18,
    notification: true
}

const userPreference = {
    font: 24,
    notification: false
}

const settings = {
    ...defaultSettings,
    ...userPreference
}

console.log(settings)
/*
  {
    theme: "dark",
    font: 24,
    notification: false
  }
*/
Enter fullscreen mode Exit fullscreen mode

With Functions

If you don't know the how much numbers of arguments passing by user in function you can use rest Parameter to collect all those arguments with ease. It give array to you which containing all passed arguments.

In function call for passing collections items individually use spread operator for that. It spread each items for you.

// Rest Operator
const sumAll(...nums){
    return nums.reduce((acc,crr)=>acc+=crr, 0)
}
console.log(sumAll(2,4,6,3)) // 15

// Spread operator
const nums = [2,4,6,3]
const max = Math.max(...nums)
console.log(max) // 6
Enter fullscreen mode Exit fullscreen mode

Summary

Spread: Getting out items form container
Rest: Putting in items from container
Spread: Used for data creating or passing
Rest: Used for captureing items


Now you fully understand what is the main difference between rest or spread operators. With this knowledge you can combine those operators use in you workflow. It gives you flexibility to work with arrays and objects for effectivly.

Top comments (0)