I have small function logically output should be 1 but i am getting 10 .. Can any one help me out with this logic.
var a=1;
function foo() {
if(!a){
var a=10;
}
console.log(a);
}
foo();
Output is coming 10 not 1 . how.
I have small function logically output should be 1 but i am getting 10 .. Can any one help me out with this logic.
var a=1;
function foo() {
if(!a){
var a=10;
}
console.log(a);
}
foo();
Output is coming 10 not 1 . how.
It's because of something called "hoisting".
https://www.w3schools.com/js/js_hoisting.asp
JS interpret your code like this
var a=1;
function foo(){
var a;
if(!a){
a=10;
}
console.log(a);
}
foo();
In addition to hoisting as mentioned in other answers, keep in mind that when writing ES6 (by using let
or const
) your code will behave as you expect it to.
Why does this happen? Because let
and const
have block-level scoping and not function-level scoping.
let a = 1;
function foo() {
if (!a) {
let a = 10;
}
console.log(a);
}
foo();
This is why, when you use a JavaScript linting mechanism, like ESLint, you will see rules like vars-on-top
( https://eslint.org/docs/rules/vars-on-top ) specifically to avoid these types of issues.