Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a is undefined while b is 3 in var a=b=3?

Tags:

In the following code, I expected both a and b to be 3. However, a is undefined and b is 3. Why?

(function(){     var a = b = 3; })();  console.log(typeof a);//"undefined" console.log(b);//3 
like image 814
Hans Qi Avatar asked Dec 06 '14 07:12

Hans Qi


People also ask

Why is my VAR undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Why VAR should not be used in JavaScript?

Scoping — the main reason to avoid var var variables are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } .

What is the scope of VAR in JavaScript?

The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global.

How do you initialize a variable in JavaScript?

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows. Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.


1 Answers

The issue here is that most developers understand the statement var a = b = 3; to be shorthand for:

var b = 3; var a = b; 

But in fact, var a = b = 3; is actually shorthand for:

b = 3; var a = b; 

Therefore, b ends up being a global variable (since it is not preceded by the var keyword) and is still in scope even outside of the enclosing function.

The reason a is undefined is that a is a local variable to that self-executing anonymous function

(function(){     var a = b = 3; })(); 
like image 156
user2466202 Avatar answered Sep 28 '22 11:09

user2466202