Sign in
Log inSign up

Spread operator magic in Javascript?

karthik selvam's photo
karthik selvam
·Oct 15, 2021·

1 min read

what is spread?

spread is the ES6 syntax is very useful for declaring arrays and object up to my knowledge Let's see how it work and how it is used

Spread operator split into a single item and copy them here I am stressing COPY because it is very much important in this blog. We declare spread operator by three dots

const name ="karthik";
const person =[...spread]
console.log(person)// ["k","a","r","t","h","i","k"]

In the next example, we are going to see how to merge arrays by using the spread operator

const boys = ["john","ram","salman"]
const girls = ["maya","keerthi","loki"]
const newFriend = ["nakul"]

const friends = [boys,newFriend,girls]

console.log(friends) //[["john","ram","salman"]["nakul"]["maya","keerthi","loki"]]

instead of the above example, we can use

const friends = [...boys,newFriend,...girls]

console.log(friends) //  ["john","ram","salman","nakul","maya","keerthi","loki"]]

the spread operator doesn't reference the value it is copying them

How its behave when using with objects

const person ={
name : "karthik",
job : "developer"
}

const newPerson ={
...person.
city : "chennai"
}


console.log(person) // {
name : "karthik",
job : "developer"
}
console.log(newPerson) //   {
name : "karthik",
job : "developer",
city : "chennai"
}

It will not affect the original object values we came to know about this. This is what I understood about the spread operator. thank you for reading

Resources : Coding addict

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct