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.