IIFE and Global scope in javascript

B.D.

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);
zerkms

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;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

variables from IIFE accessible in global scope

JavaScript IIFE functions and variable scope

Javascript: Exposing a global object defined within IIFE

How come IIFE's this variable refers to the global scope?

Scope of global array javascript

JavaScript scope issue with global variable

Javascript IIFE, don't understand how this variable becomes global

IIFE vs noraml functions, Behave differently regarding managing variables in the global scope

IIFE vs scope braces

Are JavaScript functions in different <script>s in global scope?

Find and call javascript functions in global scope

Where are constants created in a global scope stored in JavaScript?

Scope chain in Javascript and calling nested function within the global scope

Javascript - Global scope or local scope, not able to figure it out

Javascript Questions on the function - IIFE

Javascript: how to name a IIFE

Overwriting undefined and IIFE in Javascript

what is javascript IIFE principle

Why javascript doesn't look up global scope in second case

Allow global scope to let variable from imported Javascript file

Javascript: Creating global scope functions from inside an class

Appcelerator / Titanium - Are Javascript variables polluting the global scope in controller files?

Isolating External Javascript from defining methods in the global (window) scope

In JavaScript; does a let variable declared outside of a block get a global scope?

Calling a method of a function constructor from another function in the global scope - Javascript

Javascript: While the variable is declared in global scope, it remains undefined inside the function

Changing Scope from Global to Local Breaking Javascript Program

JavaScript class definition local scope enable global code completion with tern

How to store SQL query result in a JavaScript variable to use in global scope?