JavaScript Hoisting
Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before execution. Understanding hoisting prevents unexpected reference errors.
Key Topics
- Variable Hoisting
- Function Hoisting
- Temporal Dead Zone with let/const
- JavaScript Usage in DOM
- Key Takeaways
Variable Hoisting
var declarations are hoisted but not initialized. Accessing them before assignment results in undefined
.
console.log(x); // undefined
var x = 10;
Explanation: The declaration of x is hoisted, but its assignment happens later, so it's undefined at the time of the log.
Function Hoisting
Function declarations are fully hoisted, meaning you can call them before they appear in code.
Temporal Dead Zone with let/const
Variables declared with let and const are hoisted but not initialized until their declaration is evaluated, leading to a temporal dead zone if accessed early.
JavaScript Usage in DOM
Be mindful of hoisting when organizing code that manipulates DOM elements. Declare and initialize variables before using them to avoid undefined behavior.
<!DOCTYPE html>
<html>
<head><title>Hoisting in DOM</title></head>
<body>
<h1>Hoisting Demo</h1>
<p id="display"></p>
<script>
// Avoid using variables before declaration
var msg = "Hello";
document.getElementById("display").textContent = msg;
</script>
</body>
</html>
Key Takeaways
- Declarations Moved Up: var and function declarations are hoisted.
- Initialization Late: var variables are undefined until assigned.
- let/const: Have a temporal dead zone before initialization.
- DOM Integration: Declare variables and functions before use to avoid undefined issues.