AlanH AlanH - 3 months ago 7
Javascript Question

Javascript: Function hoisting

In this example, I know that it's going to print

undefined
.

var bar = typeof foo;
var foo = function() {
console.log('abcd');
}
foo();
console.log(bar); // -> undefined


So I understand that when the variables are hoisted,
bar
remains above
foo
, but
foo
gets executed, so shouldn't the interpreter know what
foo
is?

Note: I'm trying to understand how the interpreter works. My question isn't about how to fix the above snippet.

Answer

If you account for the variable definition hoisting, your code is equivalent to this:

var bar;
var foo;

// foo does not yet have a value, so it it's still undefined
bar = typeof foo;

// foo gets a value here
foo = function() {
  console.log('abcd');
}

// since foo got a value in the previous statement, you can now execute it here
foo();
console.log(bar);

Only the variable definitions themselves are hoisted, not the assignments.

So, you can see from this ordering that when you execute bar = typeof foo that foo does not yet have a value so thus you assign undefined to bar.


Function definitions such as:

function foo() {
    console.log('abcd');
}

are also hoisted, so if you defined foo like this, then it would be a different story. But the function assignment you are using is not itself hoisted. The way you define foo, it is just a variable assignment like any other.