start page | rating of books | rating of authors | reviews | copyrights

Book HomeActionScript: The Definitive GuideSearch this book

14.2. Statement Terminators (Semicolons)

As we learned in Chapter 6, "Statements", the semicolon terminates an ActionScript statement. Although by convention you should always end your statements with semicolons, they are not strictly required in ActionScript. The interpreter attempts to infer the end of a statement if the semicolon is omitted. For example:

// These are preferred
var x = 4;
var y = 5;
// But these are also legal
var x = 4
var y = 5

The ActionScript interpreter assumes that the line breaks in the preceding code are intended as statement terminators. (Compilers in stricter languages like C would complain.) However, omitting semicolons from statements in code is somewhat like omitting periods from sentences in normal writing -- the reader will probably understand most of your sentences, but there will always be cases that lead to confusion. Not to mention it's more taxing to read. For example, consider what happens when we omit a semicolon after the return statement:

function addOne (value) {
  return
  value + 1
}

ActionScript will assume that we meant to write this:

function addOne (value) {
  return;
  value + 1;
}

Instead of returning value + 1, the function will always return undefined, because the keyword return alone is a legal statement. Even if return appears alone on a line, and even if we add a semicolon after value + 1, the return statement is still treated as a complete statement.

To avoid this type of ambiguity, it's good practice to include semicolons. Furthermore, in the specific case of the return statement, don't separate the keyword return from its expression with a line break, as that alters the statement's meaning. Therefore, the preceding example should be written as:

function addOne (value) {
  return value + 1;
}

Note that semicolons terminate individual statements but are not required where statement block delimiters (curly braces) occur. For example:

for (var i=0;i<10;i++) {  // No semicolon here
  trace(i);               // Semicolon here
}                         // No semicolon here

if(x == 10) {             // No semicolon here
  trace("x is ten");      // Semicolon here
} else {                  // No semicolon here
  trace("x is not ten");  // Semicolon here
}                         // No semicolon here

on (release) {            // No semicolon here
  trace("Click");         // Semicolon here
}                         // No semicolon here

However, the semicolon is mandatory following a function literal:

function (param1, param2, ... paramn) { statements };

The special #include directive does not allow a semicolon and will cause an error if used with one. See #include in Part III, "Language Reference".



Library Navigation Links

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