DEV Community

loading...

3 ways to clone in JS

Rupak Dey
Web Dev | React | Python
Updated on ・1 min read

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

Discussion (3)

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 Author

Sure! Will check those out. Thank you