sjmartin sjmartin - 4 years ago 144
Javascript Question

Why is Foo not a function when I defined it?

I'm guessing this is some sort of "scope" issue but I want to understand why this is the case.



function foo(){
return true;
}

function bar(){
var foo = foo();
console.log(foo);
}

var foo = foo();
console.log(foo); //returns true as expected





But when I do the following



function foo(){
return true;
}

function bar(){
var foo = foo();
console.log(foo);
}

bar(); //returns Uncaught TypeError: foo is not a function





It seems that a variable name cannot be the same as a function name. But that isn't true is it?

Answer Source

There are two concepts which should help you understand this:

The first is shadowing which means that if you define a variable name inside a scope, it will hide the same variable name (or function name) from a parent scope.

The second is hoisting which causes any variable declarations to be moved to the top of the local scope.

This code

function foo(){}

function bar(){
  var foo = foo();
  console.log(foo);
}

is equivalent to this

var foo;//will initialize foo to undefined
foo = function(){}

function bar(){
  var foo;//will shadow parent foo and initialize foo to undefined
  foo = foo(); //fails because you are trying to call an undefined object
  console.log(foo);
}

Hopefully, this makes it obvious why 'foo is not a function'. Your bar function is declaring a new foo variable (which hides the global one inside the bar scope) and then tries assigning this variable by calling itself.

You can read more about the intricacies of var here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download