Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How does JavaScript handle variable hoisting within functions?
Asked on May 26, 2026
Answer
JavaScript handles variable hoisting by moving variable declarations to the top of their containing function or global context, but not their initializations. This means you can use variables before they are declared, but they will be undefined until the line where they are initialized.
<!-- BEGIN COPY / PASTE -->
function example() {
console.log(x); // undefined
var x = 5;
console.log(x); // 5
}
example();
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The variable "x" is hoisted to the top of the "example" function, but its initialization (x = 5) is not.
- The first "console.log" outputs "undefined" because "x" is declared but not yet initialized.
- The second "console.log" outputs "5" after the initialization line.
- Hoisting applies only to declarations, not initializations or assignments.
Recommended Links:
