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();
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.
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.