0
function saySomething() {
    var greeting = "Hello";
    {
        greeting = "Howdy";  // error comes from here
        let greeting = "Hi";
        console.log(greeting);
    }
}

saySomething();
// ReferenceError: Cannot access 'greeting' before
// initialization

I understand that Reference error comes because the initialization of the greeting variable occurs in the next line. But my question is why I need to initialize it even. Since var is function scoped . I have already initialized it with var greeting = hello. I am just re-assigning it in greeting = "Howdy". var being function scoped it should be accessible inside the function. I am a beginner where am I understanding it wrong.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • 1
    It's not `var greeting` which cannot be reassigned, it's `let greeting`. The `let` declaration is hoisted at the top of the scope its in. – VLAZ Nov 24 '22 at 07:19

0 Answers0