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
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:
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.When importing an array (or object, …) from another module, you’re actually creating a reference to that array. Using
list = ["item"];
in yourindex.js
file you reassignlist
whilst.push
modifies thelist
inindex.js
and also the list reference you import intest.js
. Reassignment breaks the reference betweenindex.js
andtest.js
.index.js
still refers to the original empty array, whiletest.js
now has a reference to the new array