DEV Community

Jerry
Jerry

Posted on

5

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs