home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

6.2. Compound Statements

In Chapter 5, 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.

Although combining expressions with the comma operator is an infrequently used technique, 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 each of these compound statements contains a single substatement. Using statement blocks, you can place any number of statements within this single allowed substatement.

To execute a compound statement, the JavaScript interpreter simply executes the statements that comprise it one after another, in the order in which they are written. Normally, the JavaScript interpreter executes all of the statements. In some circumstances, however, a compound statement may terminate abruptly. This termination occurs if the compound statement contains a break , continue, return, or throw statement, if it causes an error, or if it calls a function that causes an uncaught error or throws an uncaught exception. We'll learn more about these abrupt terminations in later sections.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru