Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a variable scoping bug in NodeJS or do I just need more sleep

Working on a NodeJS project, I came a across this very unexpected behaviour that I can't figure a way around - it seems like a bug to me, but perhaps I'm simply misunderstanding how NodeJS modules operate.

I've reduced it into a testcase as follows:

mod.js module

exports.process = function(obj) { obj.two = 'two'; };

test.js file

var testObj = {one: 'one'};


console.log(['Before:', testObj]);

var cachedObj = testObj;
require('./mod').process(cachedObj);

console.log(['After:', testObj]);

Then running $ node test.js gives me this:

[ 'Before:', { one: 'one' } ]
[ 'After:', { one: 'one', two: 'two' } ]

I'm assigning the value of testObj to cachedObj, and testObj is never being passed to the module method. testObj should (as far as I can see) never be modified at all.

In fact, cachedObj should surely never be modified either, as it is never returned from the mod.process method. Where am I going wrong?

(running Node 0.6.9)

like image 635
lucideer Avatar asked Dec 27 '22 05:12

lucideer


2 Answers

It's not a bug, it's perfectly expected behavior.

Variables in JavaScript are passed by reference, so the original object is mutated by the assignment in process.

like image 187
AKX Avatar answered May 21 '23 02:05

AKX


Objects are passed by reference.

var testObj = {one: 'one'}; // <--- Object
var cachedObj = testObj; // cachedObj and testObj point to the same object,

Since cachedObj and testObj point to the same object (cachedObj === testObj is true), modifying a property of cachedObj will also result in a modified testObj.

like image 34
Rob W Avatar answered May 21 '23 01:05

Rob W