I don't exactly know what you're asking. ()
calls a function without arguments.
(function () {
console.log('Hi, I\'m in the function.');
})();
is the same as:
function test () {
console.log('Hi, I\'m in the function.');
}
test(); // call the function without any arguments
The first snippet demonstrates an IIFE (immediately-invokes function expression), which is used to create a new scope. Variables declared inside the IIFE are invisible outside the IIFE.
That's the only situation where you have empty ()
. Of course, if the ()
are not empty, they serve as a grouping operator: (3 + 4) * 5
.
This grouping operator is also used in the IIFE example above: the function is wrapped in ()
to indicate that the function
key word does not start a function declaration (which requires a name), but a function expression, which does not require a name. The following would cause a syntax error:
function () {
console.log('Hi, I\'m in the function.');
}(); // SyntaxError: function statement requires a name
That's because the parser sees the function
and thinks it's a function declaration. To tell the parser that it's a function expression, we can use operators that can only be used with expressions:
(function () {})()
+function () {}()
-function () {}()
~function () {}()