–––––––––––––––––––––––––––––––––––––––––––––––––– -->

🌑

Hi Folks.

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.

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
9
10
// 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 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 // 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.

1
2
3
4
5
6
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!

, , — Nov 24, 2020


Made with 🍺 and 🍕 by Rahul