What is hoisting in javascript ?

 In JavaScript, hoisting is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions in your code even before they are declared.

Key Aspects of Hoisting

  1. Variable Hoisting:

    • Variables declared with var are hoisted but are initialized with undefined until their declaration is encountered during execution.
    • Variables declared with let and const are hoisted too, but they are in a "temporal dead zone" from the start of the block until their declaration is encountered. Accessing them before declaration causes a ReferenceError.

        console.log(a); // undefined (due to hoisting)
        var a = 10; // ReferenceError: Cannot access 'b' before initialization
        console.log(b);
        let b = 20;
  2. Function Hoisting:

    • Function declarations are fully hoisted. You can call the function before its declaration in the code.
    • Function expressions (especially those assigned to var, let, or const) are not fully hoisted in the same way.

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

        // Function Expression
        sayHello(); // TypeError: sayHello is not a function
        var sayHello = function() {
            console.log("Hi!");
        };

How Hoisting Works

When JavaScript code is executed, the interpreter separates variable and function declarations from their assignments and moves only the declarations to the top of the scope. Assignments remain in place.

Best Practices

  • Always declare variables at the top of their scope to avoid confusion.
  • Prefer using let and const instead of var to minimize unexpected behaviors caused by hoisting.
  • Understand that function declarations are hoisted, but treat your code as if they aren't for clarity and maintainability.

Would you like examples or further clarification on any aspect of hoisting?