Apparently, "function statements" (that is, "block-level function declarations") have been standardized in ES6 (ES2015). This question contains more information about their behavior. However, before ES6 (that is, on ES5 and before), they are not standard. Read the following for more information.
In JavaScript, we have function declarations:
function someFunction(/* Some parameters */) {
// Some code
}
Function expressions:
let someVar = function someFunction(/* Some parameters */) {
// Some code
}
or
let someVar = function(/* Some parameters */) {
// Some code
}
Given those, then what is the following:
function someOtherFunction(/* Some parameters */) {
// Some code
if (/* Some condition */) {
function someFunction(/* Some other parameters */) {
// Some code
}
}
}
What is someFunction
here? Well it cannot be a function expression, because it is not on the right hand side being assigned to something. Then it must be a function declaration right? Well, wrong. A function declaration, by definition, cannot appear within a block. Since someFunction
appears inside of an if
block, it is neither a function expression, nor a function declaration. It is something called a "function statement". A function statement is a function declaration that is located in a block, instead of being located either in the global scope, or directly in the body of another function, without being nested in a block.
The implementation of the function statements are not always consistent across different JavaScript implementations. Hence, it is recommended not to use function statements, and only use function declarations or function expressions. That is, when your program logic requires defining a function within a block, use a function expression instead of using a function statement. Or, if possible, change the implementation so that it uses function declarations (that is, the functions are defined either in the global scope, or directly in other functions, without being nested in any blocks).