🚀 Variable Hoisting in JavaScript: A Step-by-Step Guide 🚀

🚀 Variable Hoisting in JavaScript: A Step-by-Step Guide 🚀

Step 1: What is Hoisting?

Variable hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during compilation. This allows you to use variables and functions before they are declared in the code.

Step 2: Declarations vs. Initializations

  • Hoisted Declarations: Only variable declarations are hoisted.
  • Undefined Until Initialized: If you reference a variable before its initialization, it will return undefined.

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

Step 3: Function Declarations

Function declarations are fully hoisted, allowing you to call a function before defining it.

greet(); // Output: "Hello"
function greet() {
    console.log("Hello");
}        

Step 4: Let and Const Behavior

  • Hoisted, but Not Initialized: Variables declared with let and const are hoisted, but they throw a ReferenceError if accessed before their declaration. This is known as the "temporal dead zone."

console.log(myLet); // Output: ReferenceError
let myLet = 10;        

Step 5: Scope Considerations

Hoisting applies to the function or global scope. Variables declared inside a function are only hoisted within that function.

function test() {
    console.log(myVar); // Output: undefined
    var myVar = 3;
}
test();        

Step 6: Best Practices

To enhance code clarity and prevent unexpected behaviors, declare all variables at the top of their scope. This leads to more readable and maintainable code.


What experiences do you have with hoisting? Share your thoughts! 👇

To view or add a comment, sign in

More articles by Ankit Yadav (Immediate Joiner)

  • Suspense- React

    What is Suspense in React? Suspense is a feature in React that helps you manage loading states in your application. It…

    1 Comment

Explore content categories