As we saw in Chapter 6, the semicolon terminates an ActionScript statement. Though by convention you should always end your statements with semicolons, they are not strictly required in ActionScript. If the semicolon is omitted, the interpreter attempts to infer the end of a statement. 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 this code are intended as statement terminators. (Compilers in stricter languages such as 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; }
Similarly, a postfix ++ or -- operator should always appear on the same line as its operand:
// Right x++ // Wrong y ++
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, and the #initclip and #endinitclip pragmas should not be followed by a semicolon and will cause an error if used with one. For correct usage, see the Language Reference.