JavaScript: function expression vs. function statement

In JavaScript, all of the variables and functions are subject to hoisting.  It simply means that the compiler will move both functions and variables to the top of its parent scope. Lets look at an example that depicts how hoisting affects function expression and function statements differently.


Both foo1 and foo2 are called before they’re declared, however only the call to foo1() works and calling foo2() throws the following exception “Uncaught TypeError: undefined is not a function”.   Lets look at how the compiler will change the above code.


Both functions are hoisted to the top and the variable foo2 used for the function expression is set to undefined first, then only assigned a function value where it was originally declared – and thus the undefined error above.

Hoisting also happens within a function scope itself, if for example you declare two variables (name and age) anywhere within your function – those two variables will be hoisted to the top of your function and set to undefined.  Therefore, it is always safer and recommended that you declare all of your variables at the top if you want to avoid surprises brought on by hoisting.