Why does the following code result in logging of b
while a
is still undefined
?
(function(){ var a=b=5; })();
console.log('b:'+b);
console.log('a:'+a);
Why does the following code result in logging of b
while a
is still undefined
?
(function(){ var a=b=5; })();
console.log('b:'+b);
console.log('a:'+a);
Share
Improve this question
asked Nov 8, 2015 at 5:58
B.D.B.D.
1081 silver badge7 bronze badges
4 Answers
Reset to default 5Because var a=b=5;
statement defines only local a
variable and in fact is interpreted like
var a = (b=5);
which equals to
b = 5;
var a = 5;
which assigns 5
to a global b
variable and defines a local a
variable.
The proper way to define 2 local variables without value repetition would be
var b = 5, a = b;
In JavaScript if you ommit the var keyword before a variable, it will be considered as global. So here b is a global variable and a is only a local to that function's scope. That's why you are getting the error while accessing the a.
Never mind, I figured it out myself as it wouldn't let me sleep.
There are 2 assignments happening within the IIFE whereas only 1 declaration.
The statement var a=b=5;
declares the variable a
with var
but simply does assignment for the other variable b
.
b
is actually never declared here, just assigned - making it a global variable.
Hence b
is accessible to the log statement outside the function, which prints its value as 5
.
In other words, under 'strict' mode, the code will look like this:
(function() {
'use strict';
var a = window.b = 5;
})();
console.log(b);
A variable can be defined in 2 ways:
- var a= 5 // first
- a=5 // Second
In first way, a
is a local variable, but in second way, it bees a global variable.
So, when you do var a=b=5
, b
is a global variable and hence retains value.