Notes on Object Reference in JavaScript. It can be quite troublesome sometimes!

Notes on Object Reference in JavaScript. It can be quite troublesome sometimes!

Daily short news for you
  • For over a week now, I haven't posted anything, not because I have nothing to write about, but because I'm looking for ways to distribute more valuable content in this rapidly exploding AI era.

    As I shared earlier this year, the number of visitors to my blog is gradually declining. When I looked at the statistics, the number of users in the first six months of 2025 has dropped by 30% compared to the same period last year, and by 15% compared to the last six months of 2024. This indicates a reality that users are gradually leaving. What is the reason for this?

    I think the biggest reason is that user habits have changed. They primarily discover the blog through search engines, with Google being the largest. Almost half of the users return to the blog without going through the search step. This is a positive signal, but it's still not enough to increase the number of new users. Not to mention that now, Google has launched the AI Search Labs feature, which means AI displays summarized content when users search, further reducing the likelihood of users accessing the website. Interestingly, when Search Labs was introduced, English articles have taken over the rankings for the most accessed content.

    My articles are usually very long, sometimes reaching up to 2000 words. Writing such an article takes a lot of time. It's normal for many articles to go unread. I know and accept this because not everyone encounters the issues being discussed. For me, writing is a way to cultivate patience and thoughtfulness. Being able to help someone through my writing is a wonderful thing.

    Therefore, I am thinking of focusing on shorter and medium-length content to be able to write more. Long content will only be used when I want to write in detail or delve deeply into a particular topic. So, I am looking for ways to redesign the blog. Everyone, please stay tuned! 😄

    » Read more
  • CloudFlare has introduced the pay per crawl feature to charge for each time AI "crawls" data from your website. What does that mean 🤔?

    The purpose of SEO is to help search engines see the website. When users search for relevant content, your website appears in the search results. This is almost a win-win situation where Google helps more people discover your site, and in return, Google gets more users.

    Now, the game with AI Agents is different. AI Agents have to actively seek out information sources and conveniently "crawl" your data, then mix it up or do something with it that we can't even know. So this is almost a game that benefits only one side 🤔!?

    CloudFlare's move is to make AI Agents pay for each time they retrieve data from your website. If they don’t pay, then I won’t let them read my data. Something like that. Let’s wait a bit longer and see 🤓.

    » Read more
  • Continuing to update on the lawsuit between the Deno group and Oracle over the name JavaScript: It seems that Deno is at a disadvantage as the court has dismissed the Deno group's complaint. However, in August, they (Oracle) must be held accountable for each reason, acknowledging or denying the allegations presented by the Deno group in the lawsuit.

    JavaScript™ Trademark Update

    » Read more

The Problem

Object Reference is a concept that represents a reference variable, which means that instead of storing the actual value, it stores the memory address & operates with data based on that address. This helps save memory for applications. However, it also comes with its fair share of troubles.

Primitive Data Types

In JavaScript, we have "primitive" data types including: undefined, null, string, number, boolean, and symbol.

Variables initialized with these values are allocated a certain memory location that is not related to each other. For example:

let name = "estacks";
let name2 = name; // estacks
name = "estacks.icu";
console.log(name); // estacks.icu
console.log(name2); //estacks

Whenever the name variable changes its value, the variables that were assigned with name will still retain their original values. This also applies to data types like number, boolean, etc.

Object & Array

Unlike Primitive Types, when there are more than one variable created to store an object, array, function, they are all pointing to the same allocated memory location.

const arr1 = ['e', 's', 't', 'a', 'c', 'k', 's'];
const arr2 = arr1;
arr1[0] = 'a';
console.log(arr2); // ['a, 's', 't', 'a', 'c', 'k', 's']

In the example above, when the first element in arr1 is changed, arr2 is also changed accordingly. Why is that?

When arr1 is declared, memory is allocated and an address is stored by it. Then arr2 is assigned with arr1. Since arr1 is an array, instead of creating a new copy of that array, arr2 simply points to the same address that stores arr1. By doing so, any changes made to arr1 will also be reflected in arr2, and vice versa, because they both point to the same location. This applies to object and function as well.

Troubles

Forgetting about the reference nature of a variable

This is probably the most common case. Declaring a variable based on another variable without realizing that the variable has a reference nature.

This is a common mistake for beginners, so when you learn about this characteristic, try to avoid declaring a variable based on another variable and make a copy instead.

const person1 = {
  name: 'Nguyễn Văn A',  
  age: 20,  
  address: {
    city: 'Hà Nội',  
    district: 'Cầu Giấy',  
  }
};
const person2 = { ...person1 };

In the above example, I just copied person1 to person2. Try changing the value of name or age in person1 and person2 will not be affected. But if you change city or district, person2 will still change accordingly. This is because address is declared with an object value, so address still has a reference nature.

To copy an object using spread syntax (...) as shown above, or many other copying methods like using Object.assign can only shallow copy the object. To copy deeply nested objects like that and avoid any reference, you can use one of the following three methods:

The first method is using JSON.parse & JSON.stringify. This is the simplest and fastest way.

const person1 = {
  name: 'Nguyễn Văn A',  
  age: 20,  
  address: {
    city: 'Hà Nội',  
    district: 'Cầu Giấy',  
  }
};
const person2 = JSON.parse(JSON.stringify(person1));

However, this is also the worst method as parsing a string into an object is not good for performance, especially if the string is large.

The second method is writing code to perform deep copy:

function deepCopy(obj) {
    if(typeof obj !== 'object' || obj === null) {
        return obj;
    }

    if(obj instanceof Date) {
        return new Date(obj.getTime());
    }

    if(obj instanceof Array) {
        return obj.reduce((arr, item, i) => {
            arr[i] = deepCopy(item);
            return arr;
        }, []);
    }

    if(obj instanceof Object) {
        return Object.keys(obj).reduce((newObj, key) => {
            newObj[key] = deepCopy(obj[key]);
            return newObj;
        }, {})
    }
}

Finally, you can use built-in libraries that have deepCopy functions such as lodash, ramda... or use the clone package available on npm.

Using a shared object

Imagine you have a config used as a default if no specific config is found, you export an object that contains those configs, and it would be catastrophic if you accidentally change the value somewhere while using it.

// config.js file
module.export = {
  appName: "estacks",  
  connection: {
    host: "0.0.0.0",  
    port: 80,  
}
// app.js file
const conf = require('./config.js');

let config = findConfig(); // null
if (!config) config = conf;
...  
// accidentally changed conf
config.connection.port = 443;

At this point, in other files that have imported config.js, connection.port will all be changed to 443.

The solution for this issue is to deep clone the config object before using it. This will prevent any accidental changes that could lead to silly bugs and take a week to debug :D.

Conclusion

Understanding Object Reference is simply understanding the nature of a reference variable. When working with reference variables, you need to be extra careful to avoid making mistakes like I did above!

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...