The spread operator in JavaScript

The spread operator in JavaScript

·

3 min read

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 ]

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

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 ]

 // 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, 
// }

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

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!

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!