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
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 .
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 { } .
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.
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.
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; })();
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