I am a bit confused here in the Variable Hoisting concept. Why does the first console.log(flag)
outputs undefined
? Shouldn't it catch the already initialised value of false moving up the scope chain?
var flag = false;
(function(){
console.log(flag);
var flag = true; // JavaScript only hoists declarations, not initialisations
console.log(flag);
if(flag){
let name = "John";
const age = "24";
console.log(name);
console.log(age);
}
//console.log(name); //ReferenceError: name is not defined ( as name is block scoped here )
//console.log(age); //ReferenceError: age is not defined ( as age is block scoped )
})();