Hoisting in JavaScript

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of thier scope before code execution. However, hoisting does not mean that the declarations are physically moved to the top. Instead, JavaScript's execution context first scans the entire code for declarations and register them in the memory before executing the code.

This means we can reference a variable or function before it is declared in the code.

How Hoisting works in Variables

  • Varibale hoisting with var

    var are hoisted but are initialized as undefined

    Example 1:

    console.log(a); // undefined
    var a = 1;
    console.log(a); // 1
    

    Example 2:

    var a;
    console.log(a); // undefined
    
    a = 1;
    console.log(a); // 1
    

  • Varibale hoisting with let and const

    Varibale declared with let and const are hoisted but are not initialized. They remain in a temporal dead zone (TDZ) from the start of the block until thier declaration is encountered. Accessing them before declaration results in a ReferenceError.

    Example:

    console.log(x); // ReferenceError: Cannot access 'x' before initialization
    let x = 10;
    
    console.log(y); // ReferenceError: Cannot access 'y' before initialization
    const y = 12;
    



How Hoisting works in functions

  • Function Declarations

    JavaScript hoists the entire function declaration to the top, making it callable anywhere within its scope.

    Example:

        hello(); // Hello, World!
    
        function hello() {
        console.log("Hello, World!");
    }
    

  • Function Expressions

    Function expressions, including arrow functions, behave differently

    Example:

        hello(); // TypeError: hello is not a function
    
        var hello = function() {
        console.log("Hello, World!");
    }
    

    In this example hello is declared using var, which is hoisted and initialized with undefined. So, if we try to invoke hello gives "TypeError".




Hoisting in Different Scopes

Scopevar Hoistinglet and const Hoisting
GlobalHoisted, initialized as undefinedHoisted, but in TDZ (ReferenceError)
FunctionHoisted, initialized as undefinedHoisted, but in TDZ (ReferenceError)
BlockHoisted, but ignores block scopeHoisted, but in TDZ (ReferenceError)