-2

I've only really seen this used in

(function () {
    // more code...
})()

and basically it works as to prevent codes getting executed before the entire block of codes between the first () was loaded and the second () is just so we can invoke the function inside the first ().

Is there any other usage for ()?

Ben Thomas
  • 3,024
  • 2
  • 16
  • 38
Aero Wang
  • 6,227
  • 9
  • 35
  • 70
  • 1
    Reading [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping) is always useful. – Teemu Jul 19 '17 at 11:59
  • ok, how does you invoke a function? – Koushik Chatterjee Jul 19 '17 at 12:01
  • It's just a function call, like any other. – Carcigenicate Jul 19 '17 at 12:03
  • 1
    The "prevent codes getting executed" explanation is wrong. The parentheses turn the function into an expression so that it can be called with the second pair of parentheses. `+function() {}()` or [whatever else](https://stackoverflow.com/a/13341710) would work just as well. – JJJ Jul 19 '17 at 12:03

1 Answers1

0

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 () {}()
PeterMader
  • 5,739
  • 1
  • 16
  • 27