0

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!

trincot
  • 317,000
  • 35
  • 244
  • 286
Susa
  • 3
  • 1
  • 1
    This has nothing to do with closure - and your second example should indeed output `undefined`. Are you perhaps entering this code directly into the console, one after the other? Because if so then it is remembering the `h1 from the first snippet, which still holds the value `1`. – Robin Zigmond Nov 11 '18 at 10:37
  • 2
    Added snippets to your question which clearly show the second script does not return 1. – trincot Nov 11 '18 at 10:45
  • "*This now returns 1*" - no, it does not? Running the snippet shows `undefined` as expected. – Bergi Nov 11 '18 at 11:09

1 Answers1

0

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

Pierre Capo
  • 1,033
  • 9
  • 23
  • It does not access the global. The expression `h`, referencing the global, is evaluated when `log`is called, and the value is passed into the function by value. – OhleC Nov 11 '18 at 15:05