Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIFE and Global scope in javascript

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);
like image 933
B.D. Avatar asked Feb 11 '26 16:02

B.D.


1 Answers

Because 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;
like image 156
zerkms Avatar answered Feb 14 '26 08:02

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!