Unveiling the Magic of Hoisting in JavaScript

Rana Muzamil
2 min readDec 17, 2023

--

Hoisting is a fascinating concept in JavaScript that can sometimes catch developers off guard. It refers to the ability to use variables and functions before they are declared in the code. While it might seem like magic, understanding the mechanism behind hoisting can greatly enhance your coding proficiency.

1. What is Hoisting? Hoisting allows you to access variables and function declarations before they are officially declared in your code. This behavior occurs during the global execution context creation phase.

2. Variable Hoisting: In the example you provided:

console.log(x); // Output: undefined
var x = 10;
console.log(x); // Output: 10

The first console.log(x) outputs undefined because during hoisting, the variable x is assigned the value undefined in the memory creation phase. It's only in the subsequent code execution phase that the actual value of x is assigned.

3. Function Hoisting: Similarly, functions are hoisted as well:

console.log(sum); // Output: function sum(a, b) { return a + b; }
function sum(a, b) {
return a + b;
}
console.log(sum(4,5)); // Output: 9

The sum function is hoisted during the memory creation phase, allowing you to call it before its actual declaration in the code.

4. Exceptions: It’s essential to note that not all types of functions are hoisted.

Arrow functions and anonymous functions are exceptions. They are treated as variables and are assigned the value undefined during hoisting.

console.log(myFunction); // Output: undefined
var myFunction = () => {
console.log("This won't be hoisted");
};

5. Best Practices: While hoisting can be a powerful tool, it’s crucial to write clean and readable code. Declare your variables and functions at the beginning of their respective scopes to avoid confusion and ensure better code maintainability.

Understanding hoisting is a key aspect of mastering JavaScript. By grasping how variables and functions are lifted to the top during the execution context creation phase, you can navigate through your code with greater confidence. Keep coding!

--

--