What is Hoisting in JavaScript 🚀
Let's learn about one of the most asked interview questions of JavaScript

Hey folks 👋🏼 Today we are going to look at one of the intriguing features of JavaScript. Whether you are interviewing for a frontend role or a backend role, this is one of the top questions asked in an interview. So let’s dive in and shed light on this fascinating concept 🔍
⬆️ What is Hoisting?
Well, Hoisting is simply JavaScript’s way of moving variable and function declarations to the top of their scope during the compilation phase. This way the variables and functions can be called even before they are declared! However, we must keep in mind that only declarations are moved to the top, but assignments and initializations are not!
📦 Variable Hoisting
When it comes to variables, JavaScript hoists them to the top of the scope and gives them the value of ‘undefined’. So if you use a variable before its declaration, it won’t throw an error. Instead, the value of the variable will simply be undefined. However, hoisting works only with variables declared with ‘var’ and does not work for variables declared with ‘let’ or ‘const’.
console.log(a); // Output: undefined
console.log(b); // Error: Uncaught ReferenceError: b is not defined
console.log(c); // Error: Uncaught ReferenceError: c is not defined
var a = 10;
let b = 20;
const c = 30;
⚙️ Function Hoisting
Hoisting is not just limited to variables but even functions can get hoisted! So you can call functions before declaring them. Kinda like magic✨. However, if functions are used as expressions, then they are not hoisted.
funcOne(); // Output: Hello World!
funcTwo(); // Uncaught ReferenceError: funcTwo is not defined
function funcOne(){
console.log("Hello World!");
}
let funcTwo = function(){
console.log("Hello World!");
}
While hoisting can make your code work in seemingly mysterious ways, it's essential to write clean, readable, and predictable code. To harness hoisting effectively:
🔵 Declare your variables and functions before using them to avoid confusion.
🔵 Embrace modern practices like let and const for block-scoped variables to reduce scope-related bugs
Feel free to share your thoughts and experiences with hoisting in the comments below. Happy coding and keep the magic alive! ✨💻🔧



