Skip to content Skip to sidebar Skip to footer

Does This Line Contain A Function Declaration?

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.

Solution 1:

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

  • a function expression when it appears where an expression is expected, e.g. within the grouping operator or an assignment expression (as in your code)
  • a function declaration when it appears directly in the body of a function, module, script (global code), or eval code. Since ES6, declarations can also appear as part of a StatementList, i.e. inside a block.
  • a function statement when it appears where a statement is expected. Until ES6, this term was used to distinguish it from a declaration when the function syntax appeared in a block. If not inside a block, it is basically equivalent to a declaration.

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() {}.


Solution 2:

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).


Solution 3:

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.


Post a Comment for "Does This Line Contain A Function Declaration?"