2

How come, in the first block of code, I get "Hello", but in the second block of code, I get undefined, then "bye"?

For the first block of code, I get that it is going up the scope chain to get the hoisted variable "Hello", which I get the expected result.

    var greet = "Hello";

    var sayHi = () => {
        console.log(greet);
    }

    sayHi();

However, I'm struggling to understand how come, if I declare the variable greet after the first instance of console.log, I get undefined first? Shouldn't the JS engine go up the scope chain to find "Hello" first?

        var greet = "Hello";

    var sayHi = () => {
        console.log(greet);

        var greet = "Bye"; 
        console.log(greet);
    }

    sayHi();
  • 2
    It doesn't go up, because it already finds `greet` in the current scope (the second one you declared, which is hoisted). It's still `undefined` at the time. If you use `let`/`const` instead of `var` (which you generally should), you would get an error for accessing within its TDZ. – ASDFGerte Jan 08 '22 at 14:58
  • 1
    Because the `greet` you're using in the second `sayHi` function is a **local** within that function, because you've declared it with `var`, which is hoisted to the top of the function -- but only the declaration, not the assignment, so you start out with `greet` having the value `undefined`. – T.J. Crowder Jan 08 '22 at 14:59

2 Answers2

2

There is a difference between declaration and initialization. Declaration creates the variable, initialization assigns it its initial value. The statement var greet = "Bye"; contains both things, but only the declaration is hoisted.

1

In the second block after hoisting, it is executed as below. That's why you see undefined and then Bye.

var greet = "Hello";

    var sayHi = () => {
        var greet;
        console.log(greet);

        greet = "Bye"; 
        console.log(greet);
    }

    sayHi();

Within the function, it sees the greet variable is defined in its scope. It won't look up in the scope chain as you expect.

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43