Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

Formatting ActionScript Syntax

Formatting ActionScript Syntax

Formatting ActionScript 2.0 code in a standardized way is essential to writing maintainable code, and it’s easier for other developers to understand and modify. For example, it would be extremely difficult to follow the logic of a FLA file that has no indenting or comments, as well as inconsistent naming conventions and formatting. By indenting blocks of code (such as loops and if statements), you make the code easy to read and debug.

General Formatting Guidelines

When you use spaces, line breaks, and tab indents to add white space to your code, you increase your code’s readability. White space enhances readability because it helps show the code hierarchy. Making your ActionScript 2.0 easier to understand by making it more readable is important for students as well as for experienced users working on complex projects. Legibility is also important when you are debugging ActionScript code, because it is much easier to spot errors when code is formatted correctly and is properly spaced.

You can format or write a piece of ActionScript 2.0 code several ways. You’ll find differences in the way developers choose to format the syntax across multiple lines in the ActionScript editor (the Actions panel or Script window), such as where you put braces ({}) or parentheses (()).

Adobe recommends the following formatting points to help promote readability in your ActionScript code.

  • Put one blank line between paragraphs (modules) of ActionScript.
  • Paragraphs of ActionScript code are groups of logically related code. Adding a blank line between them helps users read the ActionScript code and understand its logic.
  • Use consistent indentation in your code to help show the hierarchy of the code’s structure. Use the same indentation style throughout your ActionScript code, and make sure that you align the braces ({}) properly. Aligned braces improve the readability of your code. If your ActionScript syntax is correct, Flash automatically indents the code correctly when you press Enter (Windows) or Return (Macintosh). You can also click the Auto Format button in the ActionScript editor (the Actions panel or Script window) to indent your ActionScript code if the syntax is correct.
  • Use line breaks to make complex statements easier to read. You can format some statements, such as conditional statements, in several ways. Sometimes formatting statements across several lines rather than across a single line makes your code easier to read.
  • Include a space after a keyword that is followed by parentheses (()). The following ActionScript code shows an example of this:

    do {
    // something
    } while (condition);
  • Don’t put a space between a method name and parentheses. The following ActionScript code shows an example of this:

    function checkLogin():Boolean {
    // statements;
    }
    checkLogin();

    or

    printSize("size is " + foo + "
    "); 
  • Include a space after commas in a list of arguments. Using spaces after commas makes it easier to distinguish between method calls and keywords, as the following example shows:

    function addItems(item1:Number, item2:Number):Number {
    return (item1 + item2);
    }
    var sum:Number = addItems(1, 3);
  • Use spaces to separate all operators and their operands. Using spaces makes it is easier to distinguish between method calls and keywords, as the following example shows:

    //good
    var sum:Number = 7 + 3;
    //bad
    var sum:Number=7+3;

    An exception to this guideline is the dot (.) operator.

  • Don’t include a space between unary operators and their operands. For example, increment (++) and decrement (--), as shown in the following example:

    while (d++ = s++)
    -2, -1, 0
  • Don’t include spaces after an opening parenthesis and before a closing parenthesis. The following ActionScript code shows an example of this:

    //bad 
    ( "size is " + foo + " " );
    //good
    ("size is " + foo + " ");
  • Put each statement on a separate line to increase the readability of your ActionScript code. The following ActionScript code shows an example of this:

    theNum++;  // Correct
    theOtherNum++; // Correct
    aNum++; anOtherNum++; // Incorrect
  • Don’t embed assignments. Embedded statements are sometimes used to improve performance in a SWF file at runtime, but the code is much harder to read and debug. The following ActionScript code shows an example of this (but remember to avoid single-character naming in the actual code):

    var myNum:Number = (a = b + c) + d; 
  • Assign variables as separate statements. The following ActionScript code shows an example of this (but remember to avoid single-character naming in the actual code):

    var a:Number = b + c; 
    var myNum:Number = a + d;
  • Break a line before an operator.
  • Break a line after a comma.
  • Align the second line with the start of the expression on the previous line of code.

Note: You can control auto-indentation and indentation settings by selecting Edit > Preferences (Windows) or Flash > Preferences (Macintosh), and then selecting the ActionScript tab.

Writing Conditional Statements

Use the following guidelines when you write conditional statements:

  • Place conditions on separate lines in if, else..if, and if..else statements
  • Use braces ({}) for if statements
  • Format braces as shown in the following examples:

    // if statement
    if (condition) {
    // statements
    }
    // if..else statement
    if (condition) {
    // statements
    } else {
    // statements
    }

    // else..if statement
    if (condition) {
    // statements
    } else if (condition) {
    // statements
    } else {
    // statements
    }

When you write complex conditions, it is good form to use parentheses (()) to group conditions. If you don’t use parentheses, you (or others working with your ActionScript 2.0 code) might run into operator precedence errors.

For example, the following code does not use parentheses around the conditions:

if (fruit == apple && veggie == leek) {} 

The following code uses good form by adding parentheses around conditions:

if ((fruit == apple) && (veggie == leek)) {} 

You can write a conditional statement that returns a Boolean value in two ways. The second example is preferable:

if (cartArr.length>0) {
return true;
} else {
return false;
}

Compare this example with the previous one:

// better  
return (cartArr.length > 0);

The second snippet is shorter and has fewer expressions to evaluate. It’s easier to read and to understand.

The following example checks if the variable y is greater than zero (0), and returns the result of x/y or a value of zero (0).

return ((y > 0) ? x/y : 0); 

The following example shows another way to write this code. This example is preferable:

if (y>0) { 
return x/y;
} else {
return 0;
}

The shortened if statement syntax from the first example is known as the conditional operator (?:). It lets you convert simple if..else statements into a single line of code. In this case, the shortened syntax reduces readability.

If you must use conditional operators, place the leading condition (before the question mark) inside parentheses to improve the readability of your code. You can see an example of this in the previous code snippet.

Writing Compound Statements

Compound statements contain a list of statements within braces ({}). The statements within these braces are indented from the compound statement. The following ActionScript code shows an example of this:

if (a == b) { 
// This code is indented.
trace("a == b");
}

Place braces around each statement when it is part of a control structure (if..else or for), even if it contains only a single statement. The following example shows code that is written poorly:

// bad 
if (numUsers == 0)
trace("no users found.");

Although this code validates, it is poorly written because it lacks braces around the statements. In this case, if you add another statement after the trace statement, the code executes regardless of whether the numUsers variable equals 0:

// bad 
var numUsers:Number = 5;
if (numUsers == 0)
trace("no users found.");
trace("I will execute");

Executing the code despite the numUsers variable can lead to unexpected results. For this reason, add braces, as shown in the following example:

var numUsers:Number = 0; 
if (numUsers == 0) {
trace("no users found");
}

When you write a condition, don’t add the redundant ==true in your code, as follows:

if (something == true) {  
//statements
}

If you are compare against false, you could use if (something==false) or if(!something).

Writing a ‘for’ Statement

You can write the for statement using the following format:

for (init; condition; update) { 
// statements
}

The following structure demonstrates the for statement:

var i:Number;
for (var i = 0; i<4; i++) {
myClip.duplicateMovieClip("newClip" + i +
"Clip", i + 10, {_x:i*100, _y:0});
}

Remember to include a space following each expression in a for statement.

Writing ‘while’ and ‘do..while’ Statements

You can write while statements using the following format:

while (condition) { 
// statements }

You can write do-while statements using the following format:

do {  
// statements
} while (condition);

Writing ‘return’ Statements

Don’t use parentheses with any return statements that have values. The only time to use parentheses with return statements is when they make the value more obvious, as shown in the third line of the following ActionScript code snippet:

return;
return myCar.paintColor;
// parentheses used to make the return value obvious
return ((paintColor)? paintColor: defaultColor);

Writing ‘switch’ statements

Follow these rules when writing switch statements:

  • All switch statements include a default case. The default case is the last case in a switch statement. The default case includes a break statement that prevents a fall-through error if another case is added.
  • If a case does not have a break statement, the case will fall through (see case A in the following code example).

    Your statement should include a comment in the break statement’s place, as you can see in the following example after case A. In this example, if the condition matches case A, both cases A and B execute.

You can write switch statements using the following format:

switch (condition) {
case A :
// statements
// falls through
case B :
// statements
break;
case Z :
// statements
break;
default :
// statements
break;
}

Writing ‘try..catch’ and ‘try..catch..finally’ Statements

Write try..catch and try..catch..finally statements using the following formats:

var myErr:Error; 
// try..catch
try {
// statements
} catch (myErr) {
// statements
}

// try..catch..finally
try {
// statements
} catch (myErr) {
// statements
} finally {
// statements
}

About Using Listener Syntax

You can write listeners for events in several ways in Flash 8. Some popular techniques are shown in the following code examples. The first example shows a properly formatted listener syntax, which uses a Loader component to load content into a SWF file. The progress event starts when content loads, and the complete event indicates when loading finishes.

var boxLdr:mx.controls.Loader; 
var ldrListener:Object = new Object();
ldrListener.progress = function(evt:Object) {
trace("loader loading:" +
Math.round(evt.target.percentLoaded) + "%");
};
ldrListener.complete = function(evt:Object) {
trace("loader complete:" + evt.target._name);
};
boxLdr.addEventListener("progress", ldrListener);
boxLdr.addEventListener("complete", ldrListener);
boxLdr.load("http://www.helpexamples.com/flash/images/image1.jpg");

A slight variation on the first example in this section is to use the handleEvent method, but this technique is slightly more cumbersome. Adobe does not recommend this technique because you must use a series of if..else statements or a switch statement to detect which event is caught.

var boxLdr:mx.controls.Loader; 
var ldrListener:Object = new Object();
ldrListener.handleEvent = function(evt:Object) {
switch (evt.type) {
case "progress" :
trace("loader loading:" +
Math.round(evt.target.percentLoaded) + "%");
break;
case "complete" :
trace("loader complete:" + evt.target._name);
break;
}
};
boxLdr.addEventListener("progress", ldrListener);
boxLdr.addEventListener("complete", ldrListener);
boxLdr.load("http://www.helpexamples.com/flash/images/image1.jpg");

Where to Go from Here

Changing your workflow to incorporate best practices (or standardizing your code) can take time and patience. However, you will quickly realize the benefits to your code and workflow. If you’re just starting to learn ActionScript, use and refer to this guide frequently to help you form good habits as you learn. If you do this, you can avoid having to retrain yourself later on.

Comments