0

I am currently studying the intricacies of JavaScript with the book "You don't know JavaScript". I have come to understand the fact that vars are hoisted and lets are not. However: if I bind a function to a var, for some reason it is not hoisted. Since I am a teacher I would very much like to really grasp the logic to this language, so can anyone explain to me the logical reason why the code below wouldn't work?

foo();

var foo = function() {
    console.log("Foo!");
};

I would expect to be able to call the function, since not only would a regular function expression be allowed to be defined below to calling of that function, but also I am binding it to a var in this instance.

Help would be very much appreciated!

  • If I could expand your code to better explain the intricacies, it would look like this with the `var` hoisting. ` var foo; // undefined; variable foo is hoisted and is undefined. foo(); // calling undefined as a function // foo has been assigned a function as value foo = function() { console.log("Foo!"); }; ` – Sakibul Alam Jan 23 '19 at 05:56
  • Since you are a teacher (I'm a teacher too) and therefore wants a clear rule, here is the important info about variable hoisting, that you can find in the dupe target and in several other answers: JavaScript hoists the variable *declaration*, not the variable *initialisation*. – Gerardo Furtado Jan 23 '19 at 05:59
  • The problem here is that you don't understand hoisting, not that you don't understand why the function wasn't hoisted :-) Hoisting does not mean that the *initialization* is brought up to the top, but instead that the *declaration* was. That is to say, hoisting protects your code from a ReferenceError being called, but the variable remains undefined until it is initialized. The equivalent code (in one line) to what you wrote is `var foo; foo(); /* foo is undefined TypeError foo is not a function */ foo = function () { ... };`. I hope this helps! – Leroy Stav Jan 23 '19 at 06:00
  • To continue your train of thought, `console.log(a); var a = "test";` results in `undefined` and `console.log(a++); var a = 0;` results in `NaN`... this is, again, because in both cases `a` is undefined *when it is referenced* because it hasn't been initialized yet, merely declared. – Leroy Stav Jan 23 '19 at 06:04

0 Answers0