Understanding Pass by Reference within Objects through Extend in Javascript with underscore.js Library

When working with Javascript and using the extend function in the underscore.js library, I am curious about what happens in relation to memory. Consider this example:

var obj = {hello: [2]};
var obj2 = {hola: [4]};
_.extend(obj, obj2)
obj2.hola = 5;
console.log(obj) // The value of hola still remains as `[4]`

I am puzzled by the fact that even after manipulating obj2, hola's value remains unchanged when inspecting obj. I expected the value to update because of pass by reference...

In my mind, here is a visualization of the process:

  1. The extend function copies the key hola into obj:

    obj = {hello: [2], hola: TBD}

  2. My assumption is that hola now points to the value [4], hence I believe obj would be

    obj = {hello: [2], hola: #0x93490234}

This is why I expected to see a value of 5 under obj. Can you help me understand where my visualization might be going wrong?

Furthermore, could you explain why the above scenario differs from this simpler example (which I grasp conceptually)?

var obj2 = {hola: [4]};
var obj = obj2;
obj2.hola = 5; // Upon console.logging obj, it will display hola equals 5

Answer №1

Perhaps this explanation will clarify things:

Let's differentiate between two fundamental concepts: values and bindings. A value represents data, such as a string, number, boolean, object, etc. Each value is stored in memory with a specific address.

A binding acts like a container or label that points to an address.

  • When we assign a value to a binding, we are actually assigning the address of the value
  • When we access a binding, we retrieve the value stored at that address

For example:

var a = 42;

a is a binding, and 42 is a value. Assuming 42 is located in memory at 0x1, then a essentially holds the address 0x1.

When we try to read the value, for instance:

console.log(a);

We look at address 0x1 to retrieve the actual value.

Now what occurs when we "assign a binding to another binding," like bar = foo?

var foo = 42; // 0x2
var bar = foo;

The value 42 resides at 0x2. Thus, foo stores the address 0x2. When we assign one binding to another, we essentially copy the address held by the binding. Consequently, after var bar = foo;, both foo and bar point to the same address 0x2. If a new value is assigned to foo, like so:

foo = 21;

Then foo now holds a new address (e.g., 0x3).

This change does not impact the address held by bar.

The same principle applies to object properties as well.


Mutable values

You may be wondering why both foo and bar change in the following scenario:

var foo = [42];
var bar = foo;
foo.push(21);
// bar also has [42, 21]

Assuming [42] is stored at memory location 0x4.

Here's how this differs from the earlier example:

We did not assign a new value to foo.

Instead, we accessed the array (located at address 0x4) via foo and made changes to it. Mutable values can be modified directly, meaning the bits at that memory location can be altered.

Following the call to foo.push,

foo</code still retains the address <code>0x4
, as does bar.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to successfully change the Span Class

My webpage has the code snippet below, but it's not functioning as expected. I have tried two methods to change the span's class attribute, but they aren't working. Could someone please help me identify where the issue lies? :) <script l ...

The jQuery functions are unable to function properly when retrieving AJAX data

I am currently working on a script that inserts a record into my database using AJAX. After inserting the data, it is posted back in the following format... Print "<li>"; Print "<span class='cost'>" . $bill. "</span> "; Print ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

What is the best way to show nested labels on separate lines simultaneously?

Despite attempting to utilize the map method as suggested in my research, it appears that it may not be suitable for the structure I am working with: const stepLabels = [ { labels1: ['First One'] }, { labels2: ['Second One', 's ...

Unravel the ReadableStream object in nextjs 13 api route

I am encountering an issue with my server-side code where a value I am sending is not being interpreted correctly. My project is utilizing the experimental App directory feature of NextJS. //src/app/api/auth/route.js export async function POST(req, res) { ...

Error in NextJS: Attempting to access a length property of null

Does anyone have insights into the root cause of this error? warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works TypeError: Cannot read properties of null (reading 'lengt ...

What steps should I take to implement the features I want using Node.js?

My request is as follows: I need to pass an array of IDs to a function that will perform the following tasks: Check if a document exists in MongoDB. If it does, move on to the next ID. If not, create a document with the specified ID. If all the IDs ...

Obtain the unique identifier of the chosen option using material-ui's autocomplete feature

I am currently implementing the autocomplete feature using material-ui. The data in the "customerList" displayed in the search field works fine. However, I am facing an issue with retrieving the "ID" number of the selected data. My goal is to obtain the ID ...

What is the process for loading this image?

While browsing through this stunning website, I came across a feature that caught my eye. Can someone please explain how the designer displayed the "The magic is loading" effect: The image vanishes once the site has finished loading completely. ...

Customizing Magnific Popup: Changing showCloseBtn and closeOnBgClick settings during display

Is there a way to customize the behavior of an open instance of a magnific popup? I want to have different settings for when the popup is closable and when it should be prevented from closing. It appears that these options are only available during initial ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

Storing JSON information within a variable

I'm currently working on an autocomplete form that automatically populates the location field based on the user's zipcode. Below is the code snippet I've written to retrieve a JSON object containing location information using the provided zi ...

What is the best way to customize the functionality of the Done (node-dialog-ok) button in node-red when it is

I have created a custom node and I want to trigger some specific actions when the 'Done' button (with id: node-dialog-ok) in the editor-tray-toolbar is clicked, instead of its default functionality. Is it possible to override the onclick event o ...

Placing a Fresh Item into a Designated Slot within an Array

Imagine having a MongoDB collection that consists of an array of objects being retrieved from an Angular Resource. [{_id: "565ee3582b8981f015494cef", button: "", reference: "", text: "", title: "", …}, {_id: "565ee3582b8981f015494cf0", button: "", ref ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

Generate a blank image using the canvas.toDataURL() method

I've been attempting to take a screenshot of this game, but every time I try, the result is just a blank image. var data = document.getElementsByTagName("canvas")[0].toDataURL('image/png'); var out = document.createElement('im ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Next.js Pre-rendering Issue: Error encountered when trying to access properties of a null object

Using Next.js for a React application (full code available here.) Encountering an unusual error while running next build, showing errors related to prerendering on five pages: spenc@WhiteBoxu:~/workout-tracker$ next build info - Loaded env from /home/spe ...