Home >Web Front-end >JS Tutorial >How Does JavaScript Function Hoisting and Scoping Affect Variable Assignment and Retrieval?

How Does JavaScript Function Hoisting and Scoping Affect Variable Assignment and Retrieval?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 17:08:13350browse

How Does JavaScript Function Hoisting and Scoping Affect Variable Assignment and Retrieval?

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 function b() declaration is hoisted to the top of the global scope.
  • The var a = 1 statement defines the global a variable.
  • The inner function a() declaration is also hoisted within the b() function and behaves like var a = function () {};.
  • The a = 10 statement reassigns the local a variable within b().
  • When you call alert(a), it returns the global a variable, which has not been modified and remains its original value of 1.

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!

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