DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on

Spread operator

If you're looking to conveniently make a shallow copy of objects in javascript(meaning one level deep), my recommendation is to use the spread operator.

From MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

It looks like this:

let array = [1,2,3]
let arrayCopy = [...array]
console.log(arrayCopy)
// expected output: [ 1, 2, 3 ]

Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays,

We can take the content for objects and copy them as well, like so:

let obj = {id: 234}
let objCopy = {...obj}
console.log(objCopy)
// expected output: { id: 234 }

Another way to use the spread operator is to pass it into a function call:


let func = (x,y,z) => {
  console.log(`${x} + ${y} + ${z} = `,x+y+z)
}
let array = [1,2,3]
func(...array)
// expected output: 1 + 2 + 3 =  6

We can also concatenate arrays easily:

let arr1 = ["a","b","c"];
let arr2 = ["d","e","f"]
let arr3 = [...arr1,...arr2]
console.log(arr3)
// expected output: ["a","b","c","d","e","f"]

So there you have, an easy and effective way to take and manipulate the contents of an object. For deeper copies, I suggest using well known js libraries such as lodash.

Top comments (0)