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

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c225-2c2f7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c225-2c2f7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?