0

I understand how objects are passed by reference in Javascript. In the following code my function changes a property of an object. It changes in the global scope as expected. I understand it.

let a = {name:'blah1'};

function something(obj1) {
  obj1.name = 'blah2';
  console.log(obj1);  // prints {name:'blah2'}
}

something(a);
console.log(a); // prints {name:'blah2'}

In the following code, I rather pass another object to my function and make my first object equal to the second. This time it does not change in global scope. How can I understand this?

let a = {name:'blah1'};
let b = {name:'blah2'};

function something(obj1, obj2) {
  obj1 = obj2;
  console.log(obj1); // prints {name:'blah2'}
}

something(a,b);
console.log(a); // prints {name:'blah1'}
Ravish Verma
  • 211
  • 2
  • 8
  • 3
    An assignment operation like `obj1 = obj2` breaks any object references, ie `obj1` no longer has any reference to `a` but instead now points to the same reference as `obj2` (`b`). Also, the scope of that assignment is only applicable to your `something` function – Phil Mar 16 '21 at 22:18
  • "I understand how objects are passed by reference in Javascript.". IMHO your misunderstanding comes from this statement. Objects are not passed by reference. Reference is passed by value. – Yury Tarabanko Mar 16 '21 at 22:23

2 Answers2

0

In the second code sample, you're not making the "first object equal to the second." You're simply overriding the variable obj1. That's why a hasn't changed when you print it.

EDIT: Just realized Phil beat me to it in his comment. If he ends up posting an answer, accept/upvote his, not mine.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
0

The scope of obj1 and obj2 is limited to the function, something. In other words, the scope of the following execution is limited to the function, something:

obj1 = obj2;

Within the function, obj1 will now reference the same object which obj2 was referencing and therefore now you can bring a change into that object using obj1 e.g.

let a = {name:'blah1'};
let b = {name:'blah2'};

function something(obj1, obj2) {
  obj1 = obj2;
  console.log(obj1); // prints {name:'blah2'}
  obj1.name='Ravish';
}

something(a,b);
console.log(a); // prints {name:'blah1'}
console.log(b) // prints {name:'Ravish'}

but outside the function, these references (i.e. obj1 and obj2) do not exist; that is why console.log(a) prints {name:'blah1'}.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110