JavaScript - Problem With Function Hoisting

javascript

JavaScript allows two ways of defining a function.  In the first method, called 
"function declaration", a new function is defined:

function foo() { ... }

This function has a name, foo.  Functions defined like this are hoisted.  
Regardless of where we define a function in the current scope, JavaScript would 
act as if the function was defined up front.  So:

foo(); // call the function before it is defined

function foo() { ... }

is perfectly valid.

The second way to define a function is by using a function expression.  In this 
case, provide a function definition in the context where JavaScript would 
expect to see an expression:

var foo = function foo() { ... }

Functions defined like this are not hoisted.  So:

foo(); // call the function before it is defined

var foo = function foo() { ... }

is not valid.

Functions defined as function expressions do not need to have names.  However, 
if we do provide a name, we won't be able to call the function by this name, 
but the function will use name when reporting errors.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License