Home > Web Front-end > JS Tutorial > Why Are My Global JavaScript Variables Undefined Inside Functions?

Why Are My Global JavaScript Variables Undefined Inside Functions?

DDD
Release: 2024-12-04 22:53:12
Original
438 people have browsed it

Why Are My Global JavaScript Variables Undefined Inside Functions?

JavaScript Variable Hoisting: Uncovering the Mystery of Undefined Global Variables

When working with JavaScript variables, it's easy to encounter surprising behavior. One such instance is when a global variable appears to have an undefined value within a certain function.

Example:

var value = 10;
function test() {
    console.log(value); // A
    var value = 20;
    console.log(value); // B
}
test();
Copy after login

Output:

undefined
20
Copy after login

Explanation:

The behavior stems from JavaScript Variable Hoisting, which automatically moves variable and function declarations to the top of the current scope. This means that:

  • The global variable value is hoisted to the top of the test function.
  • At point A, the program prints the value of the local value variable, which has not yet been initialized.
  • At point B, the program correctly prints the value of the newly initialized local variable.

In effect, the code behaves as if it were written as:

var value;

function test() {
    console.log(value); // undefined
    value = 20;
    console.log(value); // 20
}
Copy after login

Side Note: Function declarations also undergo hoisting. This is why you can call a function before it is declared, unlike variable assignments.

Conclusion:

Variable hoisting should be considered when working with JavaScript variables. By understanding this behavior, developers can avoid unexpected undefined values in their code. Additionally, resources such as Ben Cherry's "JavaScript Scoping and Hoisting" can provide further insights into this fundamental aspect of JavaScript.

The above is the detailed content of Why Are My Global JavaScript Variables Undefined Inside Functions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template