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

jareechang

Jerry

Posted on March 29, 2023

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!

💖 💪 🙅 🚩
jareechang
Jerry

Posted on March 29, 2023

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

Sign up to receive the latest update from our blog.

Related

How JavaScript works
javascript How JavaScript works

November 8, 2024

A Beginner's Guide to JavaScript Closures
javascript A Beginner's Guide to JavaScript Closures

November 5, 2024

Type Coercion in JavaScript Explained
javascript Type Coercion in JavaScript Explained

November 18, 2024

Introduction to Asynchronous JavaScript
javascript Introduction to Asynchronous JavaScript

October 14, 2024

Strings -- Manipulating the Immutable.
javascript Strings -- Manipulating the Immutable.

November 15, 2024