skip to Main Content

I have two files here:

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 don’t understand why list not being updated in test.js.
The one fix I found was to use list.push("item"); instead of list = ["item"];.
I have no idea why this is happening.

3

Answers


  1. To achieve the expected behavior, where the list length is updated correctly in test.js, you should use the push method or another method that modifies the existing array, instead of assigning a new array. Here’s how you can do it:

    // test.js
    const list = [];
    
    export function addItemToList(item) {
        list.push(item); // Add the item to the existing array
    }
    
    export function getListLength() {
        return list.length;
    }
    
    Login or Signup to reply.
  2. Your code assigns a completely new array to the value of list. However, the exported value was a reference to the original array. Updating the local variable in the "index" module does not change the value of the variable in the "test" module, in other words.

    Login or Signup to reply.
  3. When importing an array (or object, …) from another module, you’re actually creating a reference to that array. Using list = ["item"]; in your index.js file you reassign list whilst .push modifies the list in index.js and also the list reference you import in test.js. Reassignment breaks the reference between index.js and test.js. index.js still refers to the original empty array, while test.js now has a reference to the new 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search