JavaScript: The Definitive Guide

Previous Chapter 5
Statements
Next
 

5.2 Compound Statements

Earlier, we saw that the comma operator can be used to combine a number of expressions into a single expression. JavaScript also has a way to combine a number of statements into a single statement, or statement block. This is done simply by enclosing any number of statements within curly braces. Thus, the following lines act as a single statement and can be used anywhere that JavaScript expects a single statement.

{
    x = Math.PI;
    cx = Math.cos(x);
    alert("cos(" + x + ") = " + cx);
}

Note that although this statement block acts as a single statement, it does not end with a semicolon. The primitive statements within the block end in semicolons, but the block itself does not.

Combining expressions with the comma operator is an infrequently used technique in JavaScript. On the other hand, combining statements into larger statement blocks is extremely common. As we'll see in the following sections, a number of JavaScript statements themselves contain statements (just as expressions can contain other expressions); these statements are compound statements. Formal JavaScript syntax specifies that these compound statements contain a single substatement. Using statement blocks, you can place any number of statements within this single allowed substatement.


Previous Home Next
Expression Statements Book Index if

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell