Hoisting in JS


Theoretical Questions:

  1. Define hoisting in JavaScript. How does it affect variable and function declarations?
  2. What is the difference between hoisting for var, let, and const?
  3. Explain how function expressions and function declarations are treated differently by hoisting.
  4. Does hoisting occur in JavaScript ES6+? If so, how has it changed?
  5. Can variables declared with let and const be accessed before their declaration due to hoisting? Why or why not?
  6. Explain the concept of the "Temporal Dead Zone" (TDZ) in the context of hoisting.

Implementation-Based Questions:

  1. What will be the output of the following code? Explain why.

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

    Expected output: undefined

    Explanation: Variable x is hoisted but not initialized.

  2. Predict the output and explain:

    console.log(a);
    let a = 5;
    
    

    Expected output: ReferenceError: Cannot access 'a' before initialization

    Explanation: Variables declared with let are in the Temporal Dead Zone.

  3. Write code to demonstrate how a function declaration is hoisted versus a function expression.

    foo();
    function foo() {
        console.log("I am hoisted!");
    }
    
    bar();
    const bar = function() {
        console.log("I am not hoisted!");
    };
    
    

    Expected output:

    I am hoisted!
    TypeError: bar is not a function
    
    
  4. Fix the following code to avoid hoisting-related issues:

    console.log(userName);
    var userName = "John";
    greet();
    function greet() {
        console.log("Hello, " + userName);
    }
    
    
  5. Create an example that explains hoisting of a function inside a block:

    if (true) {
        test();
        function test() {
            console.log("Hoisting inside a block!");
        }
    }
    
    
  6. Debug the following code to resolve the hoisting issue and explain the fix:

    console.log(num);
    var num;
    num = 20;
    console.log(num);
    
    

Closures