When it comes to function declaration statements and function instantiation expressions, there is a key difference. While both involve the use of the keyword function
, a declaration statement cannot be directly used as a reference to a function. On the other hand, an instantiation expression is part of the expression grammar, allowing it to be freely used in that context as a reference to a function because that's what it ultimately evaluates to.
An example of this distinction can be seen here:
(function a() {
}).bind(this);
However, without utilizing the return value from .bind()
, this construct may not serve much practical purpose.
In JavaScript, if the first token in a statement is function
, then it signifies a function declaration statement. Conversely, if the initial token is something other than function
, it could be another type of keyword-introduced statement (for
, return
, var
, try
, etc.), or an expression statement. In the case of an expression (or any expression within a different context), function instantiations function as part of the expression grammar and their value can be used as references to functions.
To simplify this concept further, let's imagine a scenario where the only way to instantiate a function in JavaScript is through a function expression. In other words, every use of the function
keyword would create a function instance and return a reference to that function as its output.
Considering the nature of expressions and their role in computing values, when you require a specific value like 5
within an expression, you simply insert it and move on. For instance, merely stating 5;
is a valid expression and does not result in a syntax error.
Similarly, in our hypothetical JavaScript world without function declaration statements,
function foo(a, b) {
return a + b;
};
would essentially do nothing. The function would be created but immediately discarded since the reference to the instantiated function is not stored in a variable or utilized elsewhere. In such circumstances, you'd typically utilize
var foo = function(a, b) {
return a + b;
};
as the preferred approach.
Despite these considerations, JavaScript does incorporate function declaration statements. By delineating a statement beginning with the keyword function
as distinct from an expression statement containing a function instantiation, the language design allows for clearer differentiation between the two. Although alternative strategies could have been implemented (such as employing a different keyword), the potential for confusion remains.
Note that within the realm of JavaScript programming, some developers strongly advocate for using var
declarations for functions, highlighting the subjective aspect of coding style preferences.