JavaScript Variable Hoisting: Exploring Undefined Global Values
This article explores the surprising behavior of global variables in JavaScript, particularly when they appear to have undefined values within functions.
The Case:
In the example below, the global variable value is initialized to 10. However, when it is accessed within the test function, it logs undefined.
var value = 10; function test() { //A console.log(value); var value = 20; //B console.log(value); } test();
Output:
undefined 20
Hoisting in JavaScript:
The phenomenon behind this behavior is known as JavaScript variable hoisting. It dictates that all variables declared within a function are "hoisted" or moved to the top of the function's scope, even if they are declared after their usage.
In the example above, the value variable is hoisted to the top of the test function. However, only its declaration is lifted, and not its assignment (initialization). Thus, when console.log(value) is called, it accesses the hoisted but unassigned variable, resulting in undefined.
Explanation:
This behavior can be understood through the equivalent code:
var value; // Global function test() { console.log(value); // Accessing the hoisted but undefined value value = 20; // Local assignment console.log(value); // Accessing the locally assigned value }
Side Note: Hoisting of Functions:
Hoisting also applies to function declarations. If a function is called before it is declared, it will still execute, even though it has not yet been assigned to its identifier.
For example:
test("Won't work!"); // Error test = function(text) { alert(text); }; // Function assignment
The first call to test fails because the function is not declared at that point. However, the second call succeeds as the function is hoisted and assigned after the first call.
Conclusion:
JavaScript's hoisting mechanism can lead to unexpected results, especially when accessing global variables within functions. Understanding the nuances of hoisting is crucial for writing robust and error-free JavaScript code.
The above is the detailed content of Why Does My Global JavaScript Variable Appear Undefined Inside a Function?. For more information, please follow other related articles on the PHP Chinese website!