Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is one variable undefined outside of the IIFE while the other is not?

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
like image 978
spratap124 Avatar asked Dec 03 '22 10:12

spratap124


1 Answers

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.

like image 94
Pointy Avatar answered Apr 27 '23 22:04

Pointy