I was playing with IIFE and I'm confused. The value of a
is undefined
but b
is not. Why am I able to access the value of b
outside of IIFE?
(function(){
var a = b = 3;
})();
console.log("a defined? " + (typeof a !== 'undefined')); // false
console.log("b defined? " + (typeof b !== 'undefined')); // true
Declaration syntax can be confusing, because it looks like the syntax for ordinary expressions. It is, however, different.
var a = b = 3;
is parsed as
var a = (something);
In this case, something
is b = 3
, so it's exactly as if your function looked like
b = 3;
var a = b;
The "naked" b = 3
without var
or let
or const
creates an implicit global variable. Thus b
is visible outside the function, while a
is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With