Reputation: 14507
I am learning Javascript. Trying to understand code,
function foo (){
var a = b = {name: 'Hai'};
document.write(a.name +'<br>');
document.write(b.name +'<br>');
a.name = 'Hello';
document.write(a.name +'<br>');
document.write(b.name +'<br>');
}
The output is as follows,
Hai
Hai
Hello
Hello
While it is true that the assignment takes from Right to Left, the updates are impacting on both directions. Is this how it works? Can someone explain this?
Upvotes: 0
Views: 70
Reputation: 23859
This is because a
and b
both refer to the same object {name: 'Hai'}
. When you change one, the changes will be reflected in both the variables.
var a = b = {name: 'Hai'};
The above statement is essentially similar to this one (except what @NinaScholz pointed in her answer):
var b = {name: 'Hai'};
a = b;
This way, a
and b
both point to the same object in memory, and hence, update in one reflects to the other automatically.
Read more about how an object works in the documentation here. To read more about objects and references, refer to this link.
Upvotes: 6
Reputation: 386620
It's a bad style (and does not work) to try to declare variables in one joint assingment, because the inner variable is declared in global scope, not as local variable.
function foo (){
var a = b = {name: 'Hai'};
document.write(a.name +'<br>');
document.write(b.name +'<br>');
a.name = 'Hello';
document.write(a.name +'<br>');
document.write(b.name +'<br>');
}
foo();
console.log(b);
In strict mode, you get an error, because you use a variable without declaring.
'use strict';
function foo (){
var a = b = {name: 'Hai'};
document.write(a.name +'<br>');
document.write(b.name +'<br>');
a.name = 'Hello';
document.write(a.name +'<br>');
document.write(b.name +'<br>');
}
foo();
console.log(b);
The real order of execution is
var a = (b = {name: 'Hai'});
first evaluate the inner expression and then the outer assingment
Upvotes: 5