Recent Post:
Categories:
Hoisting is a special feature in JavaScript that allows you to use variables and functions before they are actually declared in your code. It’s like if you could see and use a toy before you put it on the shelf! This can be a bit tricky, so let’s break it down.
When JavaScript runs your code, it first looks for all the variable and function declarations and “hoists” them to the top of their scope. This means it moves them up, but it doesn’t move the actual value or assignment.
code
console.log(name); // Output: undefined
var name = "Satyendra";
console.log(name); // Output: Satyendra
When we try to log name before it’s declared, it shows undefined. This happens because JavaScript hoisted the declaration var name; to the top, but it hasn’t assigned it a value yet. After the declaration, when we log name again, it shows "Satyendra."
code
var name; // Declaration is hoisted
console.log(name); // Outputs: undefined
name = "Satyendra"; // Assignment happens here
code
console.log(age); // Output: ReferenceError: Cannot access 'age' before initialization
let age = 10;
Here, trying to log age before it’s declared gives an error! This is because let is hoisted but not initialized, so it’s in a "temporal dead zone" until it gets its value.
code
// let age; // Declaration is hoisted but not initialized
console.log(age); // Throws an error
let age = 10; // Initialization happens here
code
greet(); // Output: Hello!
function greet() {
console.log("Hello!");
}
We can call the function greet() before we declare it, and it works! This is because function declarations are fully hoisted, meaning both the declaration and the body are moved to the top.
code
function greet() { // Declaration is hoisted
console.log("Hello!");
}
greet(); // Now we can call it
code
sayHi(); // Output: TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi!");
};
Here, trying to call sayHi() before it’s declared gives an error. This happens because while the declaration var sayHi; is hoisted, the assignment of the function happens later, so it’s still undefined when we call it.
var sayHi; // Declaration is hoisted sayHi(); // Throws an error because it's undefined sayHi = function() { // Initialization happens here console.log("Hi!"); };
var: Declarations are hoisted to the top, but the assignment happens where it is defined.
let and const: Declarations are hoisted, but they cannot be accessed before their initialization (temporal dead zone).
Function Declarations: Both declarations and definitions are hoisted, so you can call them before they appear in the code.
Function Expressions: Only the variable declaration is hoisted, not the assignment, leading to potential errors if you try to call them before assignment.