var a = 2;
var b = function(){
console.log(a);
var a = 1;
};
b();
When I call b, it prints undefined. What is the reason?
var a = 2;
var b = function(){
console.log(a);
var a = 1;
};
b();
When I call b, it prints undefined. What is the reason?
Inside a function, var
declares a function-scoped variable. That means it's visible to the function. The entire function. That means you are print out the variable before assigning a value to it.
var a = 123;
(function () {
a = 456; // Changes the function's "a"
console.log(a); // Outputs the function's "a": 456
var a; // At compile-time, declares a function variable named "a".
})();
console.log(a); // Outputs the global "a": 123
Along the same line, repeating the declaration doesn't do anything. The following prints out 123
.
(function () {
var a = 123;
var a;
console.log(a); // 123
})();
The var a
in your code is a variable declaration that declares a variable within the scope of its containing function. Due to variable hoisting, variable declarations (like var a
) are hoisted to the top of their containing function. While any declaration is hoisted, assignments to that variable are not hoisted, Thus, your code is equivalent to:
var a = 2;
var b = function(){
var a; // hoisted declaration; declares `a` within this function scope
console.log(a);
a = 1; // not-hoisted assignment
};
b();
Since a declared variable is undefined
until it is given a value, this code logs undefined
.
You have this:
var a = 2;
var b = function(){
console.log(a);
var a = 1;
};
During the run time it becomes:
var a = 2, b;
b = function(){
var a; // new variable declaration with no value assigned
console.log(a); // You used it new "a" without assigning any value
a = 1;
};
Inside the function the a
is a new variable because of var
keyword and JS
is taking this new a
in account which is undefined not the global a
. Tow variables with same name, one is outside the function (in global scope) and another is inside the function. Since there is a new variable available inside the function so it's being used in console.log(a)
but no value assigned.
You may read JavaScript Scoping and Hoisting and var on MDN
.