What do you call these patterns? What is the difference between them? When would you use each? Are there any other similar patterns?
(function() {
con
In this case they are all semantically identical. The ECMAScript specification contains the full production rules, so this is a gross simplification.
Also note that I am ignoring the named function's name (x
) as the name is not used; it could be referenced within the body but since it is a FunctionExpression (via the grammar production) it would never (in a correct JS implementation) contaminate the containing scope - see the comments.
(function() {
console.log(this); // window
})();
(function x() {
console.log(this); // window
})();
var y = (function() {
console.log(this); // window
})();
var z = function() {
console.log(this); // window
}();
Reduced (the bodies are inconsequential in this case, they all "return undefined"):
(function() {})();
(function x() {})();
var y = (function() {})();
var z = function() {}();
Reduced (in the ECMAScript grammar FunctionExpression
is a production rule, but here I use it to mean "an expression that is a function"):
FunctionExpression()
FunctionExpression()
var y = FunctionExpression()
var z = FunctionExpression()
Ignoring the assignment of the result (which would always be undefined
) it can be seen that all forms are the same.
Happy coding.