Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (the current script or function). Variables and function declarations are processed before any code is executed, which affects how and when you can safely use them.
var variables are hoisted and initialized with undefined.let and const are hoisted but not initialized and stay in the temporal dead zone (TDZ) until their declaration line.var) are not safely callable before the assignment line.When a JavaScript file or function runs, the engine first performs a creation phase, where it scans for variable and function declarations. During this phase:
var declarations are created and set to undefined.let and const declarations are created but left uninitialized in the TDZ.In the execution phase, JavaScript runs line by line. Accessing a var before its declaration gives undefined, while accessing let/const before their declaration throws a ReferenceError.
var
console.log(x); // undefined
var x = 5;
console.log(x); // 5
let
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // 10
greet(); // "Hello there!"
function greet() {
console.log("Hello there!");
}
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi!");
};
const
console.log(z); // ReferenceError: Cannot access 'z' before initialization
const z = 10;
console.log(z); // 10
var example: In the creation phase, x is created and set to undefined. So the first console.log(x) prints undefined. After the assignment, it prints 5.let and const examples: y and z exist in memory but are uninitialized in the TDZ. Accessing them before their declaration line throws a ReferenceError.greet function is hoisted, so it can be called before its definition.sayHi is hoisted and set to undefined. When you try to call sayHi() before the assignment, you're effectively doing undefined(), which causes a TypeError.let and const to avoid accidental hoisting-related bugs.var variable and log it before and after the declaration. Observe the output.let and const and note the difference.var and try calling it before and after assignment.