Home >Web Front-end >JS Tutorial >Why Does This JavaScript Code Alert '1' Instead of '10'?
Understanding JavaScript Hoisting and Scoping through an Intriguing Example
In a recent article, Ben Cherry sheds light on JavaScript's intriguing concepts of hoisting and scoping. To illustrate, he presents the following code:
var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a);
Expectation vs. Reality
Intuitively, one might expect the alert to display "10" because the function a is declared within b. However, the browser displays "1" instead.
Delving into Hoisting and Scoping
Hoisting is a phenomenon where functions are moved to the top of their scope. This means that the following code gets rewritten by the interpreter:
function b() { a = 10; return; function a() {} }
Interestingly, JavaScript also allows for variable declaration within functions using the syntax function a() {}. This is equivalent to var a = function () {};.
Understanding the Execution Sequence
The code essentially functions as follows:
Therefore, the alert displays "1" instead of "10" as the global variable a is unaffected by the changes made to the local variable a within the function.
The above is the detailed content of Why Does This JavaScript Code Alert '1' Instead of '10'?. For more information, please follow other related articles on the PHP Chinese website!