Consider the following examples:
var company = 'Apple',
log = console.log;
function f1() {
log(company);
var company = 'Twilio';
log(company)
}
function f2() {
log(company());
function company() {
return 'Zynga';
}
}
function f3() {
log(company());
var company = function() { return 'RIM'; };
}
log(company);
log('---');
f1();
log('---');
f2();
log('---');
f3();
The output from firebug is:
"Apple"
---
undefined
"Twilio"
---
"Zynga"
---
TypeError: company is not a function
So why is hoisting in f3 giving me the error while others are working just fine?
Let’s rewrite your
f3function to show what it would look like after variable hoisting:becomes:
Now you can see that you are attempting to execute an undefined variable, not a function (hence the “not a function” error).
Note that this is difference from the output of
f2because function declarations are hoisted as a unit.