I have read the following
Hoisting of var
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that if we do this:
console.log (greeter); var greeter = "say hello"
it is interpreted as this:
var greeter; console.log(greeter); // greeter is undefined greeter = "say hello"
So var variables are hoisted to the top of their scope and initialized with a value of undefined.
But what happens with this (undefined) They move at the top then why it is "undefined"?
if (true) {
console.log(hi)
}
var hi = 1
If they are pushed up, they would also have to be "read" first, wouldn't they?
Javascript only hoists declarations. The initialization is not hoisted.. The assignment only happens after your if
condition.
This is also why some JS developers prefer let
over var
. If you use let
, you will get a very clear error saying the variable cannot be
if (true) {
console.log(hi);
}
let hi = 1;
//Uncaught ReferenceError: Cannot access 'hi' before initialization
The declaration is hoisted, but the assignment isn't.
It's really the same as the second example in your quote. So it's the equivalent of:
var hi;
if (true) {
console.log(hi)
}
hi = 1
So hi
is still undefined at the log statement.
This article has some good discussion and examples: https://blog.logrocket.com/demystifying-function-and-variable-hoisting-in-javascript/