Home >Web Front-end >JS Tutorial >Why Does This JavaScript Code Return '1'?
Javascript Function Scoping and Hoisting: Unveiling the Mystery
In the realm of JavaScript, understanding function scoping and hoisting is crucial for unraveling complex code. Let's delve into an example that sparked the question, "Why does this code return '1'?"
var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a);
Function Hoisting: Unraveling the Secrets
Function hoisting is a curious mechanism that whisks function declarations to the top of their scope. In our example, the function b gets hoisted to the global scope, morphing it into:
function b() { function a() {} a = 10; return; }
Variable Scoping: Confined to the Scope
Now, let's shed light on variable scoping. In our code, a is declared with var in the global scope and then redefined within b. When a variable is declared inside a function, it's only accessible within that function's scope.
In our case, the variable a redefined inside b is local to the function. Thus, the original global a remains unaffected.
The Misunderstood Behavior: A Deeper Dive
At first glance, the declaration function a() {} might seem like a function declaration. However, it's actually equivalent to var a = function() {};, defining a function-like object. This means that function a() {} doesn't create a function named a but rather reassigns the existing a variable with a new function.
Uniting Hoisting and Scoping
Combining function hoisting and variable scoping, our code essentially does the following:
Therefore, the alert displays "1" because the a used within b is a local variable that doesn't affect the global a.
The above is the detailed content of Why Does This JavaScript Code Return '1'?. For more information, please follow other related articles on the PHP Chinese website!