Variable ascension#
The way a JavaScript engine works is it parses the code, gets all the declared variables, and then runs them line by line. As a result, all variable declarations will be promoted to the header of the code, which is called variable promotion.
console.log(a);
var a = 1;
Copy the code
The above code first uses the console.log method to display the value of variable A on the console. The variable a has not yet been declared and assigned, so this is an error, but it does not actually report an error. Since there is a variable promotion, what really runs is the following code.
var a;
console.log(a);
a = 1;
Copy the code
The final result is undefined, indicating that variable A is declared but not yet assigned.
annotation#
JavaScript provides two ways to write comments: a single-line comment that starts with //; The other is a multi-line comment placed between /* and */.
Also, because JavaScript has historically been compatible with annotations of HTML code,
are also considered legal one-line comments.
x = 1; <! -- x =2;
--> x = 3;
Copy the code
In the above code, only x = 1 is executed; everything else is commented out.
Note that –> is considered a single-line comment only at the beginning of the line, otherwise it would be considered a normal operation.
function countdown(n) {
while (n --> 0) console.log(n);
}
countdown(3)
/ / 2
/ / 1
/ / 0
Copy the code
In the code above, n– > 0 is actually treated as n– > 0, so it prints 2, 1, 0.