0
 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?

  • in javascript all objects are considered as references .. you can able to understand it while cloning one object to another by simply assigning as obj1 = obj2 any change in obj2 will be reflected in obj1 as obj2 will be a reference to obj1 – AB Udhay Jul 22 '16 at 08:46
  • Thank you for your answers! I solved immediately... –  Jul 22 '16 at 08:50

2 Answers2

1

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.
Mario Santini
  • 2,905
  • 2
  • 20
  • 27
0

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

Oskar Szura
  • 2,469
  • 5
  • 32
  • 42