What is Hoisting in JavaScript?
Hoisting is the behavior of moving declarations to the top of their scope before the code is executed.
Hoisting with var:
Variables declared with var are hoisted and initialized with undefined.
Example:
<script>
console.log(name);
var name = "Raksha";
</script>
Output:
undefined
Hoisting with let:
- Variables declared with let are hoisted but not initialized.
- They remain in the Temporal Dead Zone (TDZ) until the declaration is reached.
What is Temporal Dead Zone?
- TDZ (Temporal Dead Zone) is the period between entering a scope and the point where a let or const variable is declared and initialized.
- During this period, the variable exists in memory, but JavaScript does not allow access to it.
Example:
<script>
console.log(age);
let age = 21;
</script>
Output:
ReferenceError: Cannot access 'age' before initialization.
Hoisting with const:
- Variables declared with const are hoisted but not initialized.
- They remain in the Temporal Dead Zone (TDZ) until the declaration is reached.
- const behaves similarly to let.
Example:
<script>
console.log(PI);
const PI = 3.14;
</script>
Output:
ReferenceError: Cannot access 'age' before initialization.
Top comments (0)