Questions about the order in which JS is executed.

I see one thing I don"t understand in the article https://www.cnblogs.com/highs. in [declaration and execution order of js functions and variables].

does not understand why the value of alert at line 3 is undefined?.

my idea is that during the precompilation period, js gets the declared var a, which is just a declaration and no assignment.
then the precompilation ends.
then start executing the code from the top to the bottom: execute the first line of var axiom 1, and then execute f () further. When you call the f method: alert (a), isn"t the first line already executed, does an already have a value?

or did I go around some bend that I didn"t come out?

ask for advice

Jun.02,2021

variable declaration promotes
when the third line executes, look for a . At this time, you will look for a in the scope at this time. It just declares that the value is not assigned, so it is undefined

.
 

1. The function promotes
function f () {
var a;
alert (a)
a = 3
alert (a)
}
var a;
2. Assign
function f () {
var a;
alert (a)
a = 3
alert (a)
}
var a;
a = 1;

when the first alert (a) is executed, js will find a from the scope, and there is an an in the scope of its own function, so when it is found, it will no longer look for the whole world. At this time, an is undefined, and the second alert (a) has been assigned a value of 3.

at this time, print 3.

Menu