Why do variable in an inner function return nan when there is the same variable name at the inner function declared after log

This is due to hoisting

The declaration of a in the inner function is hoisted to the top of the function, overriding the outer function's a, so a is undefined

undefined++ returns NaN, hence your result.

Your code is equivalent to:

function outer() {
    var a=2;

    function inner() {
        var a;
        a++;
        console.log(a); //log NaN
        a = 8;
    }

    inner();
}

outer();

Rewriting your code in this way makes it easy to see what's going on.


Because var is hoisted through the function, you're essentially running undefined++ which is NaN. If you remove var a = 8 in inner, the code works as expected:

function outer() {
  var a = 2;

  function inner() {
    a++;
    console.log(a);
  }
  inner();
}
outer();