Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How does variable hoisting work in JavaScript functions?
Asked on Jan 26, 2026
Answer
Variable hoisting in JavaScript refers to the behavior where variable declarations are moved to the top of their containing function or global scope during the compile phase. This means you can use variables before they are declared in the code.
// Example of variable hoisting
function example() {
console.log(value); // Outputs: undefined
var value = 10;
console.log(value); // Outputs: 10
}
example();Additional Comment:
✅ Answered with JavaScript best practices.- In the example, the declaration "var value" is hoisted to the top of the "example" function, but the assignment "value = 10" is not.
- The first "console.log" outputs "undefined" because the variable is declared but not yet assigned a value at that point.
- Hoisting applies to "var" declarations. "let" and "const" are also hoisted but not initialized, leading to a "Temporal Dead Zone" if accessed before declaration.
- Always declare variables at the top of their scope to avoid confusion and potential errors.
Recommended Links:
