The value of an object is replaced when a general method is called for the second time

I seem to be missing a fundamental concept in programming as I am encountering an unusual issue that I have never faced before.

Let me illustrate my problem through this code snippet:

var result = {abc: 10, cde: 20, efg: 30};
var final_result = {};
var customFunction1 = function(results){
  console.log(results);
  return results; // result= {abc: 10, cde: 20, efg: 30}
};
var customFunction2 = function(results){
 results.cde = 100;
 results.efg = 500;
 return results; // {abc: 10, cde: 100, efg: 500}
};
final_result.result1 = customFunction1(result);
final_result.result2 = customFunction2(result);
console.log(final_result);

In the code above, I'm passing the "result" object as a parameter to functions and storing the returned value in "final_result.result1". However, this value gets overwritten when I call another function with the same parameters. The output I am currently receiving is:

{"result1":{"abc":10,"cde":100,"efg":500},"result2":{"abc":10,"cde":100,"efg":500}}

The expected output should be: {"result1":{"abc":10,"cde":20,"efg":30},"result2":{"abc":10,"cde":100,"efg":500}}

I'm puzzled why the value of "final_result.result1" is being overwritten by "result.result2".

JSBin http://jsbin.com/mepizecuka/edit?js,console
Plunkr http://plnkr.co/edit/BF0UNnacV9UeXtyk3stI?p=preview

If anyone could provide some assistance, it would be greatly appreciated.

Answer №1

When you pass the same object to the same reference and then change it, there is no override happening. Let me illustrate this with an example.

var obj = {a:100};
var holder = {};
function changeValues( object )
{
    object.a = 5;
}
console.log(JSON.stringify(obj));
holder.test = obj; // our object is now assigned to holder.test.
holder.test2 = obj;// our object is now also assigned to holder.test2.
// holder.test = holder.test2 now;

changeValues(holder.test);
console.log(JSON.stringify(obj));

If you want to pass and change the reference, you can clone the object instead.

    var obj = {a:100};
    var holder = {};
    function changeValues( object )
    {
        object.a = 5;
    }
    console.log(JSON.stringify(obj));
    holder.test = jQuery.extend({}, obj); // now our object is cloned;
    holder.test2 = obj;// our object is still assigned to holder.test2.
    // holder.test is not equal to holder.test2 now;

    changeValues(holder.test);
    console.log(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now you have a different object at holder.test...

Answer №2

The code in question appears to be functioning correctly without any issues.

This behavior is typical of JavaScript (as well as many other languages) where arguments are passed by reference.

When you initially create the result object, it is a reference type in JavaScript. This means that the same reference will be shared across all functions.

Imagine that your result object has been assigned a reference A in memory. When you pass this to the first function, it's the reference A that gets passed. Since you're not modifying it, the returned output still points to A with the values remaining the same. The same reference A is then assigned to final_results.result1.

Subsequently, passing the result to

function2</code means the same reference <code>A
is passed again. However, this time some values are changed on it. These changes affect the reference and will reflect wherever that reference is used. The modified output is then assigned to final_results.result2.

In essence, the final_result object now consists of 2 properties that both point back to the same memory reference A. Hence, any modifications made after the second function call impact both properties.

To summarize: Objects and arrays in JavaScript are passed by reference, while primitive types like number and string are passed by value. If the initial data had been a primitive type (e.g., a number like var result = 20), such issues wouldn't have arisen.

As for addressing this issue, @Burak has provided one solution already. There are additional approaches worth exploring as well; perhaps you can discover them yourself.

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

Modify Javascript to exclusively focus on SVG paths

I successfully created an SVG animation using JSFiddle, but when I transferred the SVG to Shopify, the Javascript that animates the path stopped working. It seems like the issue is with the JavaScript targeting all paths on the page instead of just the sp ...

Determining the navigation changes within a React browser

Hi there, I'm using browserHistory.goForward() and browserHistory.goBack() to navigate forward and backward in my app with arrow buttons. However, I need a way to determine if the route has actually changed after executing browserHistory.goForward/goB ...

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

Amend the value in the database

I am looking to adjust a value in my database by clicking on an image on my webpage. Can someone guide me on how to achieve this using JavaScript and AJAX? ...

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...

"JavaScript encountered an Uncaught TypeError: Cannot read property 'style' of undefined

Looking to create a local time clock using HTML, here is the code: <body> <div class="container text-center"> <div class="row"> <div class="col-xs-12 col-sm-6"> & ...

A guide on extracting data from a mongoose model and assigning it to a variable in a manner similar to the MVC design pattern

Below is an example of MVC framework code in PHP. I'm seeking advice on how to implement a similar process in Node.js using Mongoose. I am working with Node.js, MongoDB, and REST API development. Controller file: <?php class Myclass { public fu ...

Performing multiple ajax calls simultaneously in JavaScript using the React framework

Within my React application, I am faced with the challenge of handling an array of parameters (such as IDs) that need to be passed as parameters in a queue of ajax calls. The issue arises when this array exceeds 1000 items, causing the browser page to beco ...

Establish a connection that mirrors the previously clicked hyperlink

I am attempting to create a functionality where a link can return to a specific link that matches the one clicked on a main page. For example: <a href="link.html" onclick="store this link in memory" target=home></a> <a href="the stored lin ...

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

How to effectively utilize $emit in Angular?

Whenever I use {{callData}} in my HTML, the result of $scope.callData doesn't seem to be functioning properly. Is there something wrong with my code? I would greatly appreciate any help in resolving this issue. phonecatControllers.controller(&apos ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Implement a procedure for printing a page once the columnize operation has been completed

Hello, I have run into a problem that I need help with. Currently, I am trying to print a page after the function "columnize" has finished its task. However, the print function is executing before the columnize function completes. How can I ensure that t ...

Having issues with the onclick() function not functioning properly with Jquery?

Yesterday, I successfully integrated some Jquery code into my website. However, when I attempted to add more code today for a new feature, everything seemed to stop working. Even the code that was functioning perfectly yesterday has now ceased to work. The ...

Listening to JavaScript Events with SWT Browser Widget: A How-To Guide

We are currently developing an RCP application that integrates a SWT Browser. Our goal is to establish communication between the browser and the RCP Application. Specifically, we want the RCP Application to listen for events triggered by user actions in th ...

What is the best way to retrieve the value of an UL LI element using jQuery

I'm struggling to retrieve the value of a ul li listbox in a function, and I can't seem to figure out how. Here is my code: <ul class="dropdown-menu" id="newloc"> <?php $res_add = DB::table('res_br')-& ...

Utilize the `multiselect` false attribute in conjunction with the `checkboxCell

In my current setup, I am using an ng-grid with the showSelectionCheckbox: true property along with a customized checkboxCellTemplate. If I decide to remove the checkboxCellTemplate, I achieve the desired functionality where only one checkbox can be selec ...

Implementing conditional statements in Puppeteer web scraping

Attempting to extract data from a table... Each country name is wrapped in an <a> tag, however some are not. Unfortunately, when the structure of the HTML changes, the program crashes Code => https://i.sstatic.net/zW3Cd.png Output => https: ...