Updating global variable in JavaScript at inappropriate times

Within this code:

window.g_b_editEnable = false;
window.g_a_PreEditData = 'hello';

 function EditRow(EditButton){
       if(!window.g_b_editEnable){
                 window.g_b_editEnable = true;
                 var a_i_Pos = a_o_table.fnGetPosition( EditButton.parentNode );                        
                 aData = a_o_table.fnGetData( a_i_Pos[0] );
                 console.log(window.g_a_PreEditData);
                 window.g_a_PreEditData = aData;
                 console.log(window.g_a_PreEditData);
                 aData[0] = '<button type=submit name=save>Save</button><button onclick=ResetTableFields(this) name=reset>Reset</button>';
                 for(count = 1; count < aData.length; count++){
                   aData[count] = '<input type=text value='+aData[count]+'></input>';
                 }
                 a_o_table.fnUpdate( aData, a_i_Pos[0], undefined, false, false);
                 console.log(window.g_a_PreEditData);
          }else{
                 return 1;
          }
  }

I was attempting to utilize a global variable (window.g_a_PreEditData) to store a value and pass it to another function.

However, within the mentioned function, I save the value of a local variable in the global one, then update the local variable. Strangely, the global variable also gets updated simultaneously with the local one.

The displayed console logs are as follow: Hello (initialization value) Value1 (local variable's value) Value2 (local variable's updated value)

I intended for it to display: Hello Value1 Value1

If I create a new variable like an array called 'aNewData' to store the updated values instead of modifying aData directly, the global variable window.g_a_PreEditData remains unaffected. But why does this unexpected behavior occur? My understanding was that JavaScript passed variables by value rather than reference. Therefore, once the global variable is assigned the local values, any further changes made to the local variable should not affect the global one unless reassigned... or so I thought!

Could someone enlighten me on why this anomaly is happening? Thank you!

Answer №1

One thing to note is that Javascript passes objects by reference, not by value.

Take a look at this particular line of code:

window.g_a_PreEditData = aData;

Instead of creating a duplicate of the object and assigning it, this line simply assigns a reference to it.

In essence, both window.g_a_PreEditData and aData will be referring to the exact same object after this line executes.

If you want them to point to different objects, you'll need to clone aData. Since aData is an array, you can achieve this by using the slice method.

window.g_a_PreEditData = aData.slice();

If aData happened to be an object, you'd have to employ a different method for cloning. This Stack Overflow question on cloning objects in javascript provides some useful insights.

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

The ngModel directive seems to be failing to bind the select element in Angular 4

One of the challenges I am facing in my application involves a form that includes various data fields such as title, price, category (select), and imageUrl. I have successfully implemented ngModel for all fields except the select element. Strangely, when I ...

Display the results of the constantly changing JSON response

I am expecting to receive a dynamic JSON response based on the provided input. Here is an example: { results: [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c487c6d7b7c266b6765">[email protec ...

What is the method for utilizing MongoDB to locate documents that correspond with a specific custom field?

I'm currently working on a task in node.js that involves searching for all documents matching a custom field. Below is the node.js code snippet: req.app.db.models.Property.find({ user: { id: req.params.id } }).exec(function(err, user) { if ...

Exclude the node_modules directory when searching for files using a global file pattern

I'm facing some challenges setting up a karma configuration file because I am having difficulty creating a glob that correctly matches my files. Within my lerna repository, there may be node_modules folders inside the packages, and it's importan ...

jQuery is unable to locate elements

Here is a JavaScript code snippet that I have: (function($, undefined) { $("a").click(function(event) { //or another elemtnt alert('Hello!'); }) })(jQuery); Also, here is the link being referenced in the code: <a href="http: ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

Using the splice method on an array is only effective when done in a specific sequence

I've encountered a small issue. I have checkboxes that correspond to different divs, and when checked, the name of the div is sent to the server. However, when unchecking the checkboxes in a specific order, the array doesn't update correctly. $ ...

Tips for sending a reply following several requests to a third-party API in Node.js

I've been tackling a project that involves making numerous requests to a third-party API and then sending an array of the received data back to the client. Since the requests to the API are asynchronous, I'm encountering an issue where if I place ...

The JSON data in ajax is not formatted correctly

Hey everyone, I'm facing a really frustrating error. I have a JSON formatted array that I'm passing from a PHP script to JavaScript through AJAX. Despite validating the JSON output, I keep encountering an error at the jQuery.parseJSON() step, whi ...

Change the blue line to a crisp, clean white

Is it possible to customize the color of the blue line that appears when clicked? class Greetings extends React.Component { render() { return <div>Greetings {this.props.name}</div>; } } ReactDOM.render( <div> <p tabInde ...

Vue JS console displays an error stating "the <li> tag is missing a closing tag."

Below is the code snippet I am currently using to change the color based on the character's name: I encountered an error indicating that the li tag was not properly closed, although it appears to be closed. However, there seems to be an issue during ...

Common reasons why you may encounter the error "Uncaught TypeError: $(...).DataTable is not a function"

I recently started working with DataTable.js, and when I tried to integrate it into my ASP.NET Core MVC 5.0 project, I encountered an error: Uncaught TypeError: $(...).DataTable is not a function After doing some research on Google, I discovered that this ...

Adjust the height to match the shortest sibling child div height

In my layout, I have multiple rows with each row containing multiple columns. Within each column, there is a div and a paragraph - the div contains an image. My goal is to set the div with the class cover-bg to the lowest height of cover-bg in the same row ...

Utilize the JSSOR Slider to dynamically pull images from an online album, such as by integrating with an RSS Feed

My main motivation for exploring this possibility is the negative impact that loading images into the slider has on my website's performance. Is there a method to import images from an externally hosted album, such as Google Picasa albums (or any othe ...

Validating Angular Forms within a NgFor loop

Consider the scenario where there is a form implemented as shown below: <form #form="ngForm"> <div *ngFor="let action of member_plan.actions"> <div class="container"> <h4 class="text-sm-center black mb-3">{{ ...

Generate a new entity using a previously imported model with A-Frame

I have successfully imported a house model in .gltf format. I am now trying to extract the floor object from this model and turn it into its own individual a-frame entity for future reference. This is necessary so that I can designate the floor as the coll ...

Why am I encountering this export issue while attempting to integrate a NextAuth.js Provider with Next.js?

Embarking on my first project in React/Next.js, I opted to employ NextAuth.js for authentication. Following the initial steps outlined in the Getting Started guide provided by NextAuth, I have successfully set up a [...nextauth].js page featuring the code ...

Open a new lead form in Crm 2013 by clicking a button and automatically passing the details of the

I have integrated an Add New Lead button into the main form on the Homepage for contacts. Clicking this button triggers a script that opens a new form and passes "Crm Parameter FirstSelectedItemId" as a parameter. By selecting a contact and clicking crea ...

Assess JavaScript for Fetch API implementation

Currently, I am utilizing node.js on Windows with the express module to create an HTML page where I need to retrieve data from a server-side function called getfiledata() (I want to keep my Javascript and text file private). I have attempted to use fetch( ...

retrieving information from server via ajax to display on chart

I am currently utilizing the jqPlot JavaScript library for generating graphs and charts in one of my applications, which can be found at . Within my application, there are approximately 5-6 pages where I have integrated this library. However, I would like ...