Hoisting Javascript
-
What is hoisting in javascript?
- Hoisting is a behavior where variable and function declarations are moved to the top of their scope before code execution.
- This means you can use a variable or function before it's declared in your code.
-
Important Points:
- Only declarations are hoisted, not initializations.
- This means that the variable or function is declared at the top, but its values is not assigned until the actual line of assignment is reached in the code.
- Function declarations are hoisted completely.
- This means you can call a function before it appears in your code.
- Variables declared with
varare hoisted to the top of their scope & initialized with a value ofundefineduntil the assignment line is reached. - Variables declared with
letandconstare also hoisted but they are not initialized.- Accessing them before their declarations results in a
ReferenceError - Hoisted but in Temporal Dead Zone Javascript
- Accessing them before their declarations results in a
- Only declarations are hoisted, not initializations.
console.log(x); // undefined
console.log(y); // ReferenceError: Cannot access 'y' before initialization
console.log(z); // ReferenceError: Cannot access 'z' before initialization
var x = 5;
let y = 10;
const z = 15;
Question
function abc() {
console.log(a); // undefined
console.log(b); // ReferenceError
console.log(c); // ReferenceError
var a = 10;
let b = 20;
const c = 30;
}
abc();