Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope during the compilation phase, before the code is executed.
Only the declarations are hoisted, not the initializations. This allows the code to reference variables and functions before they are actually declared in the code flow.
var
console.log(x); // Output: undefined
var x = 10;
console.log(x); // Output: 10
Explanation: The declaration var x
is hoisted to the top, but the assignment x = 10
is not.
let
and const
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 5;
Explanation: let
and const
are hoisted but cannot be accessed before declaration due to the Temporal Dead Zone (TDZ).
greet(); // Output: Hello!
function greet() {
console.log("Hello!");
}
Explanation: Function declarations are fully hoisted, so they can be invoked before they appear in the code.
greet(); // TypeError: greet is not a function
var greet = function () {
console.log("Hi!");
};
Explanation: Only the variable greet
is hoisted (as undefined
), not the function assigned to it.
var
is hoisted and initialized as undefined
.let
and const
are hoisted but cannot be used before initialization (TDZ).Understanding hoisting helps prevent unexpected errors and makes debugging easier. Always declare variables and functions at the top of their scope to avoid confusion.