Why doesn't a JavaScript variable update across files as expected?

I am facing an issue with two files in my project:

index.js

let list = [];

function add() {
    //list.push("item");
    list = ["item"];
    console.log("B. list length " + list.length);
}

module.exports = {
    add,
    list
}

test.js

let { add, list } = require('./index');

console.log("A. list length " + list.length);
add();
console.log("C. list length " + list.length);

Current output:

A. list length 0
B. list length 1
C. list length 0

Expected output:

A. list length 0
B. list length 1
C. list length 1

I cannot figure out why the value of list is not updating in test.js. The workaround I found is to use list.push("item"); instead of list = ["item"];. This behavior is puzzling to me.

Answer №1

When you bring in an array (or object, ...) from another module, you are essentially establishing a connection to that array. By using list = ["item"]; in your index.js file, you are reassigning the value of list, while .push modifies the original list in index.js as well as the reference to it in test.js. This reassignment severs the link between index.js and test.js. As a result, index.js continues to point to the original empty array, whereas test.js now points to the updated array.

let list = [];

function add() {
  // list.push("item");
  list = ["item"];
  console.log("B. list length " + list.length);
}

const importedList = list; // mocking require("./index");

console.log("A. importedList length " + importedList.length);
add();
console.log("C. importedList length " + importedList.length);

Answer №2

The code you've written assigns a brand new array to the variable list. This means that the exported value was originally pointing to the original array. When you update the local variable within the "index" module, it does not impact the variable within the "test" module.

This issue isn't related to importing and exporting between modules. The same scenario can be observed in this example:

let a = [1, 2, 3];
let b = a;
a = [4, 5, 6];
console.log(b); // [1, 2, 3]

Changing the reference of variable a to a new array doesn't change the value of variable b. This behavior is fundamental to how JavaScript operates.

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

Has the user successfully authenticated with Google?

Possible Repetition: How to verify if a user is logged into their Google account using API? I'm working on a website that displays a Google Calendar. My query is: Can I determine whether a user is currently logged into a Google Account? If it&ap ...

Using JavaScript, the list of items (images) will be displayed and placed into HTML panels

Below is the layout structure on my website: <div class="panel-heading"><h3 class="panel-title">Suggestions</h3></div> <div class="panel-body"> <div class="col-md-7"> <h3><span class= ...

Comparing the positions of elements in Selenium WebDriver with PHP

One of the elements on my webpage serves as a button that reveals a drop-down menu. Due to various factors affecting the page layout, there were some alignment issues between the button and the menu until a few bugs were fixed. I am now looking for a way t ...

Looking for assistance in streamlining the code

On my Drupal page, I have multiple divs and a JavaScript function that checks for content inside each one: if ($('.accred').length) { $('#accred').show(); } else{ $('#accred').hide(); } // More code follows... T ...

Ways to reduce the quality of an image before uploading it to Firebase

Having recently created a chat app with reactJs and firebase, I encountered an issue when trying to upload images with larger file sizes in MB. The images would successfully upload if they were only a few KB, but I needed a way to reduce the size of thes ...

Console log messages not displaying in Express.js app method

const express = require("express"); const app = express(); app.listen(3000, function () { console.log("Server started at port 3000."); }); app.get("/", function (req, res) { console.log("Hello, world"); const truck = "drive"; res.send("Hello, ...

Error encountered: Attempting to wrap MuiThemeProvider in App resulted in an invalid hook call

Whenever I include MuiThemeProvider in App.js, I encounter an error that prevents the page from loading. This issue is puzzling to me since I have utilized it successfully in other projects. react.development.js:1476 Uncaught Error: Invalid hook call. Ho ...

The target element is out of reach for the Puppeteer selector

When trying to extract the source of multiple images, I encountered an issue with the selectors not working properly. It seems like the elements are fake or not actually present on the page. Every page contains one of the desired elements (the main image) ...

Send Symfony2 form data via AJAX

When trying to render a form with AJAX and update existing values, I am facing an issue. Even after using the preventDefault method in my script to stop form submission, the form is still submitting. Here's the snippet of my script: $('#edit-co ...

Is there a way to alter visibility once a radio button has been selected?

I have a shape resembling a cube with 4 faces, all of which are currently visible. However, I would like to hide the other 3 faces when one face is showing. For example: I attempted setting the opacity of the other cube sides to 0 when the first radio but ...

Tips for sending a PDF created with jsPDF as an attachment in an email using asp.net c#

I'm wondering if there's a way to attach a PDF file that was generated using jsPDF and email it in asp.net C#? This is the code snippet I have in c#: MailMessage message = new MailMessage(fromAddress, toAddress); message.Subject = subj ...

Leverage the power of Shopify API to retrieve a list of all products by making a request through

My website is custom built on node.js, and I am looking to retrieve all of my products in a single GET request. Unfortunately, the Shopify buy-button feature does not allow me to display all products at once due to pagination, hindering my ability to effec ...

Proper method for retrieving and displaying information from a targeted JSON through an API

Utilizing a third-party API requires specifying the desired fields in the request. For instance: axios.get("APIURL", { params: { fields: ["username", "phone", ...etc] } }) The response is typically structured like this: { "data": [{ ...

Inserting information (either a string or integer) into a character array

Currently, I am facing an issue with adding data to an existing char array from an int or string in C++. Here is the code snippet: int num1 = 10; int num2 = 5; string temp = "Client"; char buf[64] = "This is a message for: " + temp + num1 + " " + temp + n ...

What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON: const data = { "38931": [{ "userT": "z", "personId": 13424, "user": { "id": 38931, "email": "sample", }, } ...

Determining the visibility of an element on a webpage using JavaScript and Puppeteer

I've created a framework that scans websites hosted on our servers to ensure they comply with our policies. If any prohibited content is found, we capture a screenshot along with other relevant details. However, taking a screenshot may not be possibl ...

React: Import default export as a string

Help needed with JSON data import import dataOption1 from './Option1.json' import dataOption2 from './Option2.json' async setParamsByDomain(optionUser) { await this.setState({ jsonName: "data"+ optionUser}); console.log(t ...

Using SQL commands in PHP to loop through and retrieve editable values

I currently have a Stockroom ID ($srid) that is associated with one or more Categories ($cat). //Categories have been organized into an array[] For example: Stockroom ID1 has 2 categories. If a user wants to edit and add another category, the following c ...

How come the gridApi.on.edit.beginCellEdit function in angular-ui-grid does not immediately refresh the dropdown options after being updated?

I am encountering a similar issue as described in this post Regarding the assignment of ui grid value drop-down box before beginCellEdit event fires in Angular However, I have noticed a slight difference. Even after updating the editDropdownOptionArray, th ...

What method can be used to incorporate Google Places API into a .js file without using a <script> element?

As I delve into the Google Places API documentation, I noticed that they require the API be loaded in this format: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> Is ...