wood burning stoves 2.0*
The moose likes HTML, CSS and JavaScript and the fly likes confused about javascript syntax Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "confused about javascript syntax" Watch "confused about javascript syntax" New topic
Author

confused about javascript syntax

simon tiberius
Greenhorn

Joined: Oct 30, 2012
Posts: 29
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

Joined: Jan 10, 2002
Posts: 60761
    
  65

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.

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
simon tiberius
Greenhorn

Joined: Oct 30, 2012
Posts: 29
thank you very much for the reply Mr Bibeault. It's finally clear now.
 
Don't get me started about those stupid light bulbs.
 
subject: confused about javascript syntax
 
Similar Threads
JSTL 1.1 - Get value from method of an Obj and set it to a variable
Will Clojure be popular among Java programmers?
Shorten conditions
JavaScript functions and their parentheses
Passing variables