πŸš€ Understanding JavaScript Hoisting πŸš€

Dimple Kumari
2 min readSep 25, 2023

--

Hoisting refers to the process where JavaScript moves declarations to the top of their respective scope during the compilation phase before the actual code execution.
Remember that JavaScript only hoists declarations, not initialization.

Consider the following code snippet:

console.log(myVariable);
var myVariable = 10;

You might expect this code to throw an error because myVariable is being used before it's assigned a value. However, JavaScript behaves differently due to hoisting. During compilation, the code is effectively interpreted as:

var myVariable;
console.log(myVariable); // undefined
myVariable = 10;

As we can see, the declaration myVariable is "hoisted" to the top, but the initialization remains in the same place. This means that when we log myVariable before assigning it a value, it's not an error; instead, it results in undefined.

Let vs Var

An important distinction to make is that let and const declarations are also hoisted, but they differ from var in one significant way. Variables declared with let or const are not initialized until their actual position in the code is reached. This is known as the "temporal dead zone."

console.log(myVar); // undefined
var myVar = 5;

console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 10;

Thank You for Reading!

If you found this post informative and valuable, I’d love for you to connect with me for more front-end development insights. Follow me here on Medium and connect with me on LinkedIn to stay updated on the latest in web development, design, and more.

#JavaScript #HoistingExplained #WebDevelopment

--

--

Dimple Kumari

Passionate front-end developer creating pixel-perfect web experiences. HTML, CSS, and JS enthusiast. Making the web beautiful and user-friendly. 🌐