Lexical scope of javascript

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

Why does the output here have something to do with lexical scope?

Mar.17,2021

Update:

js parses the code before execution, and all variables are declared and assigned before execution begins.

that is, all the variables are prepared first, and then executed in the order of the code.

as long as var is used, the variable is prepared early in the current scope (and below), and it is assigned earlier than any call to it.

< hr >

keyword: var variable promotion


variable declaration is elevated
this is equivalent to the fact that the variable has been declared (and assigned) before the call

what I said is not very clear ~ to supplement the
procedure is to declare that the promotion is undefined at this time
executes the assignment statement before you call (the assignment is before the call)


keyword: LHS RHS

var b;
function foo() {
    console.log(b)
}
b = 2;
foo(); //  console.log(b) b ->  -> b ->  ->  2
The

variable declares a promotion, and then executes the foo function in a reasonable order;
if you put var b = 2; after foo ();, the print result is undefined


var variable promotion

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-1eb00f3-22a2.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-1eb00f3-22a2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?