Hoisting in JavaScript

Definition:

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope during the compilation phase, before the code is executed.

How It Works:

Only the declarations are hoisted, not the initializations. This allows the code to reference variables and functions before they are actually declared in the code flow.

1. Variable Hoisting using var


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

Explanation: The declaration var x is hoisted to the top, but the assignment x = 10 is not.

2. Variable Hoisting using let and const


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

Explanation: let and const are hoisted but cannot be accessed before declaration due to the Temporal Dead Zone (TDZ).

3. Function Hoisting


        greet(); // Output: Hello!

        function greet() {
            console.log("Hello!");
        }
    

Explanation: Function declarations are fully hoisted, so they can be invoked before they appear in the code.

4. Function Expression (Not Hoisted)


        greet(); // TypeError: greet is not a function

        var greet = function () {
            console.log("Hi!");
        };
    

Explanation: Only the variable greet is hoisted (as undefined), not the function assigned to it.

Key Points:

Conclusion:

Understanding hoisting helps prevent unexpected errors and makes debugging easier. Always declare variables and functions at the top of their scope to avoid confusion.