var obj = { hi : 'hello' };
function myFunction( arg ) {
console.log( arg.hi );
}
myFunction( obj );
if I call myFunction
, does javascript engine pass obj
as reference? or copy?
Also then, how can I see that?
var obj = { hi : 'hello' };
function myFunction( arg ) {
console.log( arg.hi );
}
myFunction( obj );
if I call myFunction
, does javascript engine pass obj
as reference? or copy?
Also then, how can I see that?
Object are passed by reference not by value. So you have to be careful in changing the objects inside the functions.
You could see in my snippet here.
var o = {
'msg': 'Say Hi!'
};
function myFun(arg) {
console.log(arg.msg);
// This should not be accessible
// from global scope if is a copy
arg.msg = 'Bye';
}
myFun(o);
// Check what appened
console.log(o.msg);
// It is passed by reference.
If it's an object - it passes it as a reference (address which points to the particular object). It's gonna be the same object. Any changes applied within the function will affect the object.
In order to make a copy you can use Object.assign