While ActionScript 3.0 supports global variables and constants and also supports variables and constants local to a function, it does not support block scoping. The "Variables" section of Chapter 4 ("ActionScript Language and Syntax") of Programming ActionScript 3 describes this in more detail. In this blog entry, I'll demonstrate this with a brief example.
const aConstant:String = "GlobalConstant";
var aVariable:String = "GlobalVariable";
private function demonstrateVariableScope():void
const firstConstant:String = "firstConstant";
var firstVariable:String = "firstVariable";
const aConstant:String = "LocalConstant";
var aVariable:String = "LocalVariable";
if ( 1 )
const secondConstant:String = "secondConstant";
var secondVariable:String = "secondVariable";
"First Constant: " + firstConstant + "\n"
+ "First Variable: " + firstVariable + "\n"
+ "Second Constant: " + secondConstant + "\n"
+ "Second Variable: " + secondVariable + "\n"
+ "Global/Local Constant: " + aConstant + "\n"
+ "Global/Local Variable: " + aVariable + "\n" );
The output from running the SWF that results from compiling the above code looks like this:
This example demonstrates a couple important points about variable and constant scoping in ActionScript:
1. Like Java, local variables (variables local to a function) override variables of the same name on a more global level.
2. Unlike Java, ActionScript variables defined within a block are actually scoped to the entire function containing that block rather than to simply the block itself.
Where something like this can cause a little trouble is when a developer tries to use the same constant name in two different blocks. This will result in a compiler error ("Error: A conflict exists with definition ...") because the compiler will see the constants declared in two separate blocks within the same function as being an attempt to redefine a constant.
This is not a huge deal, but it is a subtlety that can be a surprise to a Java developer learning ActionScript.