DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

Hoisting in JavaScript | Episode 3

πŸ” 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

  1. JavaScript code runs in two phases:
  2. Memory Creation Phase
  3. Code Execution Phase

  4. During the memory creation phase:

  5. Variables declared using var are initialized with undefined

  6. Function declarations are stored in memory as they are

  7. This allows:

  8. Variables to be accessed before assignment

  9. Functions to be called before declaration

  10. Accessing a variable before assigning a value returns undefined

  11. 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)