-1

let a = 1;
function outer() {
  console.log(a);

  function inner() {
    console.log(a);
    var a = 3;
  }
  inner();

  console.log(a);
}

outer();

why 'a' is undefined in the inner function above? shouldn't it be able to find a = 1 in the first line through scope chain?

inner function is inside outer function, and outer function is inside the global scope.

Liftoff
  • 24,717
  • 13
  • 66
  • 119
facVV
  • 379
  • 1
  • 3
  • 4
  • 2
    Variable declarations are hoisted. The inner function is equivalent to `var a; console.log(a); a = 3;`. `var` declarations are initialized with `undefined`. If you used `let` you would get an actual error (thus making you aware that you made a mistake). – Felix Kling Dec 29 '20 at 20:26

2 Answers2

3

It is because of Javascript hoisting

Your inner() function is equal to -

function inner() {
    var a;
    console.log(a);
    a = 3;
}

which would obviously output undefined in the console.

0

It has to do with the scope, here is a way how you can do this..

let a = 1;
function outer() {
  console.log(a);
let newA = a
  function inner() {
    console.log(newA);
  
  }
  inner();

  console.log(a);
}

outer();
Stefan Avramovic
  • 1,365
  • 2
  • 11
  • 20