0

There below two codes print different outputs, despite the inner function not being called.

var a = 1;
function foo(){
  a= 2;
}
foo();
console.log(a);   // 2

But if I add a function with the same name, the output is different. Although I am not calling the a()

var a = 1;
function foo(){
  a= 2;
  function a(){
    a = 3;
  }
}
foo();
console.log(a);   // 1

Should not it be 2? Why it logs 1?

newbie
  • 530
  • 1
  • 9
  • 36
  • 2
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+function+declaration+hoisting) of [Javascript function scoping and hoisting](/q/7506844/4642212). – Sebastian Simon Sep 06 '21 at 20:33

1 Answers1

3

Because an identifier named a is declared directly inside the foo function, assignments to variables named a inside the foo function will reference that (local) identifier, and not any possible outer variables named a. It's like:

var a = 1;
function foo(){
  // there an identifier named `a` initialized in this scope
  var a;
  // function declarations are hoisted
  a = function a(){
    a = 3;
  }
  // assignment to local identifier `a`
  a= 2;
}
foo();
console.log(a);   // 1
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I understood and thanks for answering but I will try to put it in easy words that due to the function declaration inside `foo`, a new variable is declared inside foo with name `a` and its scope is limited to that `foo` and it doesn't affect the outer `a` at all. Without function declaration, outer `a` is updated. – newbie Sep 06 '21 at 20:44