Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How does JavaScript handle variable hoisting in functions?
Asked on Feb 18, 2026
Answer
In JavaScript, variable hoisting allows you to use variables before they are declared within their scope, typically moving declarations to the top of their containing function or global context.
<!-- BEGIN COPY / PASTE -->
function example() {
console.log(value); // undefined
var value = 10;
console.log(value); // 10
}
example();
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- JavaScript hoists variable declarations, not initializations. The "var value;" is hoisted to the top of the function, but "value = 10;" remains in place.
- The first console.log outputs "undefined" because the variable is declared but not yet initialized.
- Using "let" or "const" instead of "var" changes hoisting behavior, as they are hoisted but not initialized, leading to a "Temporal Dead Zone" error if accessed before declaration.
Recommended Links:
