DEV Community

Rupak Dey
Rupak Dey

Posted on • Updated on

3 ways to clone in JS

Objects in JavaScript are reference values, you can't simply just copy using the '='

Save It For Later! Let's begin...

const food = {a : 'apple', b : 'burger'}
Enter fullscreen mode Exit fullscreen mode


1. Spread

{...food}
Enter fullscreen mode Exit fullscreen mode


2. Object.assign

Object.assign({}, food)
Enter fullscreen mode Exit fullscreen mode


3. JSON

JSON.parse(JSON.stringify(food))
Enter fullscreen mode Exit fullscreen mode


Result

{a : 'apple', b : 'burger'}
Enter fullscreen mode Exit fullscreen mode


Do you know the difference between these 3 ways? Comment down below!



Connect with me : Github | Tutoring | Freelance Web Dev

Top comments (2)

Collapse
 
ajones_codes profile image
Andrew Jones

One difference is that JSON.stringify will break if your object has circular references - you can use a custom replacer to prevent this stackoverflow.com/questions/116166...

Collapse
 
deyrupak profile image
Rupak Dey

Sure! Will check those out. Thank you