Home >Web Front-end >JS Tutorial >Why Does This JavaScript Code Return '1'?

Why Does This JavaScript Code Return '1'?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 08:34:10988browse

Why Does This JavaScript Code Return

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:

  1. Hoists b to the global scope.
  2. Creates a local variable a within b.
  3. Reassigns the global a to 10.
  4. Alerts the global a, which has the value 1.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn