what is hosting
What is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations (not initializations) to the top of their scope (global or function) during the memory creation phase.
In reality, nothing is physically moved.
It’s just that variable and function declarations are stored in memory before code execution starts.
How Hoisting Works
JavaScript executes code in two phases for each execution context (Global or Function):
Creation Phase (Memory Allocation)
Variables (
var) are hoisted with valueundefined.Functions (function declarations) are hoisted with their full definition.
Execution Phase
Code runs line by line.
Variable assignments happen here.
Examples
1. Hoisting with var
console.log(x); // undefined
var x = 5;
console.log(x); // 5
Why undefined?
During creation phase:
x = undefined.During execution:
x = 5.
2. Hoisting with Functions
greet(); // Hello!
function greet() {
console.log("Hello!");
}
Works fine because the entire function is hoisted.
3. Function Expression (Not Hoisted Like Declarations)
greet(); // TypeError: greet is not a function
var greet = function() {
console.log("Hello!");
};
Here, only the variable name greet is hoisted as undefined, not the function body.