-2

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.

JJJ
  • 32,902
  • 20
  • 89
  • 102
app_dev
  • 74
  • 1
  • 2
  • 10

2 Answers2

4

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();
Himan
  • 379
  • 1
  • 7
0

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.

George Katsanos
  • 13,524
  • 16
  • 62
  • 98