What I know: if variables are initialized without declaration, then they are automatically initialized.
Hoisting in JavaScript only raises the declaration to the top and not the initialization.
What I tried on Google Chrome Console:
console.log(num);
Result:
Uncaught ReferenceError: num is not defined
at :1:13
Cause: Since hum isn't declared or initialized
num = 9; console.log(num);
Result: 9
Cause: Due to initialization, it is also declared and num gets its value ie 9
console.log(hum); hum = 8;
Result:
VM519:1 Uncaught ReferenceError: hum is not defined
at :1:13
What I am not able to understand:
since I have initialized hum
to 8
,it will also get declared and by hoisting in JS,the declaration of hum
is hoisted and I should be getting undefined
as result. Why isn't it happening?
JavaScript variables start with the value of undefined if they are not given a value when they are declared (or initialized) using var, let, or const.
console.log(hum); hum = 8; console.log(typeOf(hum));
this will give you undefined as its intialized but not declared.
console.log(hum); var hum = 8;
will be hoisted.
For more info,
https://medium.com/coding-at-dawn/how-to-check-for-undefined-in-javascript-bcedd62c8ad