Javascript Function Scoping and Hoisting: Unveiling the Hidden Mechanics
You've stumbled upon a perplexing example involving JavaScript scoping and hoisting. Let's delve deeper into these concepts to gain a clearer understanding.
Function Hoisting
Hoisting lifts function declarations to the top of their containing scope. In your example:
function b() { a = 10; return; function a() {} }
The interpreter rearranges this code as follows:
function b() { function a() {} a = 10; return; }
This means the inner function a() declaration is effectively placed at the beginning of the b() function, even though it appears later in the code.
Variable Scoping
In JavaScript, variables can be scoped globally or locally. Global variables are accessible from anywhere in the program, while local variables are confined within the scopes of their defining functions.
The Curious Case of Function Declarations
In your code, the inner function a() declaration within b() is interpreted as an immediate function invocation:
var a = function () {};
This effectively creates a local variable a in the b() function, which shadows the global a variable.
Putting it All Together
Combining the concepts of hoisting and variable scoping, you can visualize the execution sequence as follows:
The above is the detailed content of How Does JavaScript Function Hoisting and Scoping Affect Variable Assignment and Retrieval?. For more information, please follow other related articles on the PHP Chinese website!