About the scope of JS function?

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

the above code, why is the result 2? it should not be the foo () function called in the bar () function, so should you first look for an in the scope of bar (), and then look for it in the global scope?
I hope that the great gods who walk by and pass by can help solve their doubts. Thank you very much.

Mar.06,2021

the scope rule here is the scope rule when it is defined, not when you call it, that is, static scope

if you write:

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

that must have output 3


foo uses a


of the global variable.

you can assume: if you are asked to design a programming language, if a function is called, how do you determine its scope? The
function has two scopes: static action, which determines the scope according to where the function is written, and dynamic scope, which is dynamically determined when the function is called.

JS, like most programming languages, takes a static scope.

you can use these two related words for Google search, and a lot of blogs have discussions

.
Menu