Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the function of parantheses in javascript? [duplicate]

Tags:

javascript

I know most of people using the following script like

(function(){})();

for anonymous function call. But what's the function of the surrounding parantheses?

var g = (); // syntax error, why?
var g= (function(){}); // correct

Can anybody explain it for me?

like image 908
brian_wang Avatar asked Dec 05 '25 17:12

brian_wang


2 Answers

() is used to group an expression. When there is no expression inside, its a syntax error.

To illustrate it, see the following example.

var x = 5; // works
var y = (5); // works
var z = (); // syntax error!
like image 55
Shiplu Mokaddim Avatar answered Dec 08 '25 06:12

Shiplu Mokaddim


() is used for several things within JavaScript.

Method invocation

When used as an operator, it'll be used to call a function, optionally with a list of parameters:

var a = function() { console.log(23); }
a() // => 23

You can see this, when people use anonymous functions which are called directly to create closures. just as in your example:

(function(){})();

Although i guess most people would write it this way:

(function(){}());

to indicate, that the function is grouped and the expression is part of a whole. This leads to another use case:

Grouping an expression

() can be used to group expressions. Like this:

(1,2,3);

The empty () would be a syntax error. But this would work:

a = (1,2,3);
console.log(a); // => 3

It's the case in your example:

var g = (function(){});

g has been assigned an anonymous function as it's value. This would also work:

var g = function() {};

Same effect.

Grouping has no immediate value, but when you consider creating anonymous functions for closures, it is pretty essential:

function() {
    // your code
}(); // => Syntax Error

But this will work:

(function() {
    return 12;
}());

as the expression is grouped.

like image 30
Florian Avatar answered Dec 08 '25 06:12

Florian