π What is Hoisting?
Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope during the memory creation phase of the execution context.
β οΈ Only declarations are hoisted, not initializations.
π§ How Hoisting Works
- JavaScript code runs in two phases:
- Memory Creation Phase
Code Execution Phase
During the memory creation phase:
Variables declared using var are initialized with undefined
Function declarations are stored in memory as they are
This allows:
Variables to be accessed before assignment
Functions to be called before declaration
Accessing a variable before assigning a value returns undefined
Accessing a variable that is not declared at all throws a ReferenceError
Variable declarations β undefined
Function declarations β fully available
π Hoisting Behavior Summary
| Declaration Type | Hoisted | Initial Value |
| -------------------- | ---------- | ------------- |
| var variable | β
Yes | undefined |
| Function declaration | β
Yes | Full function |
| Function expression | β οΈ Partial | undefined |
| Arrow function | β οΈ Partial | undefined |
| Undeclared variable | β No | Error |
β
Example 1: Variable & Function Hoisting
`getName(); // Namaste Javascript
console.log(x); // undefined
var x = 7;
function getName() {
console.log("Namaste Javascript");
}`
Explanation
- getName() is fully hoisted and can be called before declaration
- x is hoisted and initialized with undefined
- No error occurs
β Example 2: Accessing an Undeclared Variable
`getName(); // Namaste JavaScript
console.log(x); // ReferenceError: x is not defined
console.log(getName); // function getName() {...}
function getName() {
console.log("Namaste JavaScript");
}
`
Explanation
- x is never declared
- JavaScript throws a ReferenceError
- Function declarations are still hoisted correctly
β Example 3: Function Expression Hoisting
`getName(); // TypeError: getName is not a function
console.log(getName); // undefined
var getName = function () {
console.log("Namaste JavaScript");
};
`
Explanation
-Function expressions behave like variables
-getName is hoisted as undefined
-Calling it as a function throws a TypeError
Top comments (0)