Reputation: 582
I have the following files in the same directory:
data.js
var anArray = [1,2];
module.exports = anArray;
mod1.js
var data = require('./data');
module.exports = data;
mod2.js
var data = require('./data');
module.exports = data;
main.js
var mod1 = require('./mod1');
var mod2 = require('./mod2');
When I do mod1 === mod2
it is true
Why is that? My initial belief was that mod1 and mod2 files should contain an array but that are different (different references to the array objects).
Upvotes: 0
Views: 51
Reputation: 23544
This is because modules are cached. Since you're referencing the same module twice, the second one is returning the exact same as the first. In your example, it's the same as doing the following:
const arr1 = [1,2]
const arr2 = [1,2]
arr1 === arr1 // true
arr1 === arr2 // false
The last line is false
because you're comparing two different arrays.
Upvotes: 1