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

Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map. My goal is to have the popup display 2 buttons: Start from Here Go to this Location The desired outcome looks like this sketch: ___________________ ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

I am looking for a way to add some color to the text within a div on my HTML page. Can you help me

Is there a way to apply background color only to the text content within this div, without styling the entire element? ...

Why am I encountering http://localhost:3000/api/auth/error?error=AccessDenied when implementing Google signin in my Next.js application?

Can someone please assist me in resolving an issue I am facing with my NextJs application using Google signin? Whenever I try to sign in, I get the error message "http://localhost:3000/api/auth/error?error=AccessDenied". Why is this happening? Here is a ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

Guide on retrieving the content type field value in Drupal and transferring it to a JavaScript file

In my custom Drupal theme, I have included a field for a SoundCloud URL with the machine name (field_soundcloud_url_). I am attempting to use a JavaScript file that will function based on the value of this variable. However, it seems to not be working as e ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

PHP: the images uploaded are not located within the designated folder

Having trouble uploading multiple images to a folder and saving them in the database? The images are not moving to the folder, even though the code works on localhost. Here is the code snippet: var abc = 0; // Declaring and defining global incremen ...

How can I retrieve the word that comes after a specific word in discord.js

Currently, I'm attempting to create a bot similar to Dad bot, but I'm struggling with implementing the "Hi __ I'm, Dad" feature. Here's the code snippet that I've put together so far: var imWords = ["i'm", "I&a ...

Guide to setting up Firebase pagination in a NextJS 13 server component

Currently, I am working on developing a product page that showcases all products and functions as a server component. The challenge I am facing is the inability to pass the last visible document snapshot required by the startAfter() query. Below is the fu ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

The timeouts persist in firing and running even after being cleared and the component has been unmounted

I am currently working on creating bus animations based on an array of coordinates. I am using setTimeout to trigger a function that moves the marker to the next coordinate. However, I am facing an issue where the functions continue to execute even after c ...

Implement an AJAX function to prompt a save dialog before initiating the download process

I'm currently programming an embedded device in C with a web server. One of the tasks I am working on is downloading files from this device. I need to download several files at once, so I've set up an AJAX request that uses a POST method and send ...

What is the best way to retain the leading zeros when creating a new Number() in JavaScript?

Hey everyone, I'm running into some issues with this specific function. const incrementString = str => { if (!str.match(/[\d+]$/)){ return str += 1 } else{ return str.replace(/[\d+]$/, match => new Number(match) + 1) } ...

Is there a way to prevent undefined properties when using .each in jQuery with a JSON object?

I am trying to populate the values of <inputs> on a webpage using data from a JSON object. http://codepen.io/jimmykup/pen/exAip?editors=101 To begin, I create a JSON object with two values - one for name and one for url. var jsonObj = []; var nam ...

Unexpected request causes a dilemma during the karma test for an Angular directive

Let's discuss a straightforward directive: 'use strict'; angular .module('app') .directive('ngEmailMask', ngEmailMask); function ngEmailMask() { var directive = { replace: true, restrict: 'EA', ...

Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt. Any bright ideas or sugges ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...