DEV Community

Cover image for The Spread operator in JavaScript
Rahul
Rahul

Posted on

The Spread operator in JavaScript

My latest post on JavaScript - Spread operator fully explained is here.


What does Spread Operator do?

It expands an iterable object into the list of arguments. (Arrays, Objects, Strings )
When ...arr is used in the function call, it 'expands' an iterable object arr into the list of arguments.

const arr = [34, 22, 13, 3]

console.log(...arr)
  // 34 22 13 3

console.log(arr)
// [ 34, 22, 13, 3 ]
Enter fullscreen mode Exit fullscreen mode

When to use Spread Operator?

Making a copy of an array object.

const arr = [34,22,13,3]

const newArr = [...arr]

console.log(newArr)
// [ 34, 22, 13, 3 ]

// Proff that ther are not same
console.log(arr === newArr)
// false
Enter fullscreen mode Exit fullscreen mode

Concatenating Arrays & Combining objects

// combining arrays

const nums = [2,5,84,3]

const newNums = [...nums, 2,865]

// Here adding 2 again does no overwrite the previous occurrence

console.log(newNums)
 // [ 2,  5, 84, 3, 2, 865 ]
Enter fullscreen mode Exit fullscreen mode


 // combining objects
 const user = {
     name = "Rahul"
     age = "16"
     gender = "male"
}

const Alex= {
       ...user,
       isAthelete: true, 
       name: "Alex"
}

// Providing the name key again overwrites the previous value of the name

console.log(Alex)

// {
//     name: "Alex"
//     age: "16"
//     gender: "male"
//      isAthelete: true, 
// }
Enter fullscreen mode Exit fullscreen mode

Finding highest number in an array of numbers.

Passing the array into the Math.max() function doesn't work but using the spread operator spreads the array into individual elements of the array.

const arr = [1,2,3,4]
console.log(Math.max(arr))
// NaN

console.log(Math.max(...arr))
// 4
Enter fullscreen mode Exit fullscreen mode

Rest Parameter vs Spread Operator

Even though both of them have the same syntax"...".
Both of them are the exact opposite of each other.
The Rest Parameter casts a list of items into an array and the spread operator expands an iterable object into its individual elements.




Thanks For Reading. Anything going in your mind? Comment down below!

Top comments (2)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.