Function Hoisting in Javascript

Context: I'm writing this as a quick reminder to myself. Sort of like when I was back in Catholic elementary school and the nuns would make us tirelessly write out our vocabulary words until our wrists were ready to fall off!

Function hoisting in JavaScript is determined based on whether you're using a function expression, or a function declaration. I'm going to let an example do the talking.

marcoExpression(); // TypeError: undefined is not a function
marcoDeclaration(); // Polo!

var marcoExpression = function() {
console.log("Polo!");
};

function marcoDeclaration() {
console.log("Polo!");
};

So, you can see from above that the Javascript interpreter treats these functions differently. With function expressions, only the variable is hoisted. With function declarations, the entire function is hoisted and as such can be called either before or after the declaration. In other words, function declarations are loaded before being executed, while a function expression itself is only loaded once it's executed.

Written on November 6, 2013