The following code:
console.log(b);
b = 2;
//"ReferenceError: b is not defined
I thought it would be undefined when printed.
According to my understanding, b = 2 does not use var, so it declares a global variable. Since the variable is declared, there will be variable declaration promotion. Why is there ReferenceError: b is not defined?
And try adding var:
console.log(b);
var b = 2;
//undefined
So it seems that using var and omitting var are not just the difference between local and global declarations?
As a newbie, please give me some advice, thank you!
There is always a sequence for code execution. . .
Additional point:
directly
b = 2
这种创建全局变量的方式,其实质是变为全局对象上的一个属性,即window.b = 2
, so there is no promotion or non-promotion; variables declared using var have declaration promotion.Ask and answer your own questions and add one more thing:
I found this sentence on mdn:
This sentence explains my confusion about why the global variable b is not promoted like a. a is a declared variable, while b is an undeclared variable that is only defined during execution, so is not promoted before execution.
Original text: https://developer.mozilla.org...
Declaration will be made in advance
will be interpreted by the compiler as
And undeclared/undefined has no chance of being promoted, so an error will be reported as soon as it is used
For these scope issues, you can read "Javascript You Don't Know" (Volume 1), it's all discussed above
Engine---
Responsible for the compilation and execution process of the entire JavaScript program from beginning to end.
Compiler---
Friend of the engine, responsible for syntax analysis and code generation.
Scope---
Another friend of the engine, responsible for collecting and maintaining a series of queries consisting of declared identifiers (variables), and enforcing a very strict set of rules that determine the impact of the currently executing code on these identifiers access rights.
When you see var a = 1;
In fact, the engine thinks there are two completely different declarations here, one is processed by the compiler at compile time, and the other is processed by the engine at runtime.
var a=1; decomposition
When encountering var a, the compiler will ask the scope whether there is already a variable with this name in the collection of the same scope. If so, the compiler will ignore the declaration and continue compilation; otherwise it will ask the scope to declare a new variable in the collection of the current scope and name it a.
Next, the compiler will generate the code required for the engine to run at runtime. These codes are used to handle the assignment operation of a=1. When the engine is running, it first asks the scope whether there is a variable called a in the current scope collection. If so, the engine will use this variable; if not, the engine will continue to look for the variable.