This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confused about javascript syntax

 
simon tiberius
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've seen the syntax:


what is this? how come there are so many parentheses? AFAIK, for statement should be accompanied by curly bracket {}, not parentheses ().
how can two parentheses group exist side by side like that (function group and myVar group)?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64629
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's really sloppy code -- I would not write it as such. But it is perfectly legal.
AFAIK, for statement should be accompanied by curly bracket {}, not parentheses ().

As with languages like Java, the braces can be left off when the body of the for loop is a single statement (as with an if statement, or while loop, and so on).

For example: if (x == 0) x = 1;

That's what's going on here. The parentheses aren't substituted for the braces; the braces have simply been omitted.

how can two parentheses group exist side by side like that (function group and myVar group)?

The construct used as the body for loop is called an immediate function. The function is declared, and then is immediately called.

The first set of parentheses encloses the function, the second encloses the parameter list for the function.

When we call a function named x, we'd usually use something like: x(213);

When calling an immediate function, the x is replaced with the function definition: (function(p){ alert(p); })(213);

Personally, I would have formatted the code differently to help make the syntax less confusing.
 
simon tiberius
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much for the reply Mr Bibeault. It's finally clear now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic