JavaScript - Problem With Function Hoisting
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.
page revision: 0, last edited: 15 Feb 2017 04:45