DEV Community

Jerry
Jerry

Posted on

Only 34% of developers got this JS concept right 😱❗️❗️

Image JS Concept poll

The question in that poll may seem simple but in reality, there is a few things going on.

If you are wondering the answer to that question is steak.

Let’s break that down.

Pass By Reference

Image Javascript Pass By Reference illustration

Objects within Javascript are pass by reference by default.

What that means is variable definition and assignment are linked to the object as a reference.

So, any changes to that object means... You are changing the original object ❗️

The reason this is not ideal is because you are mutating the value of an object for all the code using that object.

And that can lead to really hard to debug bugs.

So, what can you do about it ?

Well, that’s where cloning comes in.

Let‘s see how that works.

Object Cloning

Image Object Cloning illustration

One way to combat against this issue is through cloning of the object when re-assigning or when you are changing it.

When you clone an object, you are essentially creating a new copy of it.

So, that variable no longer references the original, it now references the new copy.

This way when you make changes to that object, it doesn’t affect the original object.

So, how do you do this in Javascript ?

Let’s look at some techniques you can use to achieve this.

Object Cloning techniques (Javascript)

Image Javascript Object Cloning Techniques

Here are 3 methods for cloning objects:

  1. Object.assign - creates a shallow copy of the object

  2. Spread operator - creates a shallow copy of the object

  3. structuredClone - creates a deep copy of the object

The difference between shallow and deep is that deep will copy all the nested objects within the object. Shallow will not do this.

And there you have it!

Remember be careful when mutating or changing references to objects.

It can leads to nasty bugs!

If you learned something new or enjoyed this article, be sure to give it a like or share with someone you know!

Top comments (0)