3 ways to clone in JS

deyrupak

Rupak Dey

Posted on May 31, 2021

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

πŸ’– πŸ’ͺ πŸ™… 🚩
deyrupak
Rupak Dey

Posted on May 31, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related