Diksha Dhote's Blog

Diksha Dhote's Blog

Rest Vs Spread operator in JavaScript, What's the difference?

Diksha Dhote's photo
Diksha Dhote

Published on Jan 14, 2022

2 min read

When we see rest and spread operator, what we see is both have three dots like this ... so aren't they are same? if not, then what makes them different?

Let's see,

Rest as the name suggests, it will have all the parameters which are remaining from arguments passed.

In the below example, odd is the first argument to the function numbers. so, the first value 3 which is passed is assigned to it. Second value 4 is assigned to even, all the values which are remaining now are assigned to rest array.

function numbers(odd, even,...rest){
console.log(odd)
console.log(even)
console.log(rest)
}

numbers(3,4,5,6,7,8,9)

image.png

As the rest gathers all remaining arguments and puts them into an array, it should be at the last position. If we try to assign it in between, it throws an error.

function numbers(odd,...rest,odd2){
console.log(odd)
console.log(odd2)
console.log(rest)
}

numbers(3,4,5,6,7,8,9)

image.png

Spread on the other hand, is used to expand iterable expressions like array or string.

let arr=[2,3,4,5]
let numbers=[1,...arr,6,7]

In the above example, We can assign arr to numbers and expand it to form a numbers array. image.png

As the string is also iterable, it returns a list of characters when passed in an array.

let str = " Hi Sunshine!"
console.log([...str])

image.png

Spread also helps to expand a list of arguments, when we have to pass something to built-in functions in JavaScript.

Suppose, we have to calculate the minimum number from the list of numbers. If we just have two or 3 numbers, we can pass directly as Math.min(47, 54, 2) and it will calculate the minimum number as 2.

what if we have too many numbers? then we need an array to store the numbers.

if we directly pass arr to Math function, which calculates the minimum number from a group of numbers, it will return NAN. Because the min() function expects a list of arguments.

let arr= [1,2,3,4]

Math.min(arr)

image.png

But here our spread operator comes to rescue which converts arr to list of arguments.

let arr= [1,2,3,4]

Math.min(...arr)

image.png

Summary

The three dots ( ... ) are the same. But when it is passed to the end of the function parameters, it becomes rest. Otherwise, it is spread.

 
Share this