Search code examples
javascriptclosureshoisting

hoisting & closure - confusion


Hoisting:

console.log(h)
var h = 1

This returns undefined, since the declaration is moved to the top, but the value is assigned after the console.log(), just like this:

var h;
console.log(h)
h = 1

This now returns 1, which is don't understand, since it's supposed to be the exact same as above in my understanding

Closure: Why can console.log() as a function not access the global var h in the first example?

would be really happy, if sb could help me out here. thank you!


Solution

  • Indeed those 2 cases are similar, so what's happening here ?

    I think you got a bit fooled by your console. Your console always log something when you execute a command anyways. You can read this post to get better acknowledges about what get returned by your console by default when you do h=1; and var h=1;.

    why can console.log() as a function not access the global var h in the first example? : It actually accesses the global h variable. But since there is not value assigned yet to h, well the console.log returns undefined which basically means that the h variable exists but the value it has is undefined. If it didn't find the h variable it would have returned instead an error saying that h is not defined which might be confusing, but is not the same as undefined