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 09, 2026
Answer
JavaScript handles variable hoisting by moving variable declarations to the top of their containing function or global scope. This means you can use variables before they are declared, but their value will be "undefined" until the assignment is reached.
<!-- BEGIN COPY / PASTE -->
function example() {
console.log(myVar); // Outputs: undefined
var myVar = 10;
console.log(myVar); // Outputs: 10
}
example();
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The variable "myVar" is hoisted to the top of the "example" function, but only the declaration, not the assignment.
- Before the assignment, "myVar" is "undefined".
- Hoisting applies to "var" declarations, but "let" and "const" are hoisted differently and do not allow usage before declaration.
- Always declare variables at the top of their scope to avoid confusion.
Recommended Links:
