weilou
weilou

Reputation: 4617

I cannot understand the parentheses in this JavaScript statement

I cannot understand the parentheses in JavaScript statement below:

({go_go: 'go'});

What does the () here mean?

I know () in function means this function is anonymous. Just like codes below. Is it right?

(function () {
    alert('something');
})();

Thank you!

Upvotes: 1

Views: 394

Answers (3)

Fenton
Fenton

Reputation: 250822

Some people are in the habit of surrounding JSON objects with parenthesis...

var jsonObject = ({go_go: 'go'});

Is the same as

var jsonObject = {go_go: 'go'};

The reason they do this is because if you are retrieving JSON objects via an AJAX call, you often need the parenthesis to prevent a common parse error.

The following line of code often causes an invalid label error:

var jsonObject =  eval(stringOfJson);

And this is usually solved as follows:

var jsonObject =  eval( "(" + stringOfJson + ")" );

And finally, the practice of wrapping an immediate function in parenthesis should look like this...

(function () {
    alert('something');
}());

And the only reason you use the parenthesis is that it makes the immediate function more obvious (as recommened by www.jslint.com amongst others!)

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318468

I think Why does JavaScript's eval need parentheses to eval JSON data? answers your question.

You don't need them if you just have a plain object literal in your code though.

In your function expression the outer () do not make the function anonymous (it already is as it has no name). However, to execute an anonymous function immediately after defining it they are necessary since function(){}(); is not valid.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1073998

In that literal example, they have no purpose, but generally they're for enclosing an expression — specifically, for ensuring that the contents of the parens are read as an expression, not as a statement.

You'll see things like that when people are using eval to deserialize data in JSON format. So for instance, they might receive a string in the form:

var s = '{"go_go": "go"}';

...and use this to deserialize it:

var o = eval('(' + s + ')');

This is an old work-around to certain issues, but you're much better off using a proper JSON parsing library, such as any of the three listed on Crockford's github page. (Crockford being the inventor of JSON.) There's one there which does some regexes to detect various malformed-JSON stuff and then uses eval, and two others that don't use eval at all. (I would never use eval when dealing with JSON from an untrusted source.)

Upvotes: 2

Related Questions