Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the value not assigned to the variable in case of an IIFE?

(function() {
    var a = b = 3;
})();

console.log(a, b);



(function() {
    var x = y = 3;
    console.log(x, y);    
})();

These are very simple program. But I'm confused why a is undefined while b has value 3 in the output of the first example program while both x and y are having the value 3 in the second example program?

like image 398
A.V.D. Kishore Avatar asked Oct 17 '25 12:10

A.V.D. Kishore


1 Answers

(function() {
    var a = b = 3;
})();

console.log(a, b);

When a IIFE is created , a function is created and is called.Here a is the local variable and variables have local scope so you cant access it outside

You havent used var in front of b so it becomes the global variable and hence is reflected outside the function scope too

like image 88
Piyush.kapoor Avatar answered Oct 19 '25 01:10

Piyush.kapoor



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!