The following line is known as a function expression in JavaScript. Does it contain within it a function declaration?
var foo = function() {};
Edit: edited for clarity.
The following line is known as a function expression in JavaScript. Does it contain within it a function declaration?
var foo = function() {};
Edit: edited for clarity.
No, it does not. Both function expressions and function declarations do define functions, and contain the function
keyword.
How they differ is basically determined where they appear in the source code, their syntax is otherwise the same. It is
Also read http://kangax.github.io/nfe/ which explain all these terms (pre-ES6 though).
For the difference between their evaluations see var functionName = function() {} vs function functionName() {}.
We can readily determine that this is not function declaration, according to ES5 section 14:
Program :
- SourceElementsopt
SourceElements :
- SourceElement
- SourceElements SourceElement
SourceElement :
- Statement
- FunctionDeclaration
A FunctionDeclaration can only be a SourceElement (a quick search for FunctionDeclaration shows no other grammatical use), and a SourceElement can only be a top-level component of a list of SourceElements (either a Program or a FunctionBody). This use of function
is nested inside of an assignment, so it cannot be a top-level SourceElement.
Furthermore, we can also rule out this as a FunctionDeclaration by its definition:
FunctionDeclaration :
function
Identifier(
FormalParameterListopt)
{
FunctionBody}
Your code does not have an Identifier, which is mandatory for FunctionDefinitions (but optional for FunctionExpressions).
A Function Expression defines a function but does not declare a function. As such the code
var foo = function() {};
defines a function and then assigns it to a variable.
Where as
function foo() {};
defines a function and declares it without the need for an assignment.