11

inspired by the question int a[] = {1,2,}; Weird comma allowed. Any particular reason? I remembered a question concerning the syntax in Adobe's Actionscript.

For some reason it is possible (at least in Flex 3) to assign a value to a variable before it was declared:

 public function foo() : void {
      a = 3;
      var a : int = 0;
 }

Does this make any sense..? Is this a bug in the Adobe FlexBuilder compiler? Or is this due to maybe some legacy to older Ecmascript editions?

Community
  • 1
  • 1
Mister Henson
  • 505
  • 4
  • 20

3 Answers3

17

An interesting implication of the lack of block-level scope is that you can read or write to a variable before it is declared, as long as it is declared before the function ends. This is because of a technique called hoisting , which means that the compiler moves all variable declarations to the top of the function. For example, the following code compiles even though the initial trace() function for the num variable happens before the num variable is declared...

Actionscript 3.0 Docs - Variables (quote found about 2/3 down the page)

Sam DeHaan
  • 10,246
  • 2
  • 40
  • 48
3

As far as I know it is the feature of Flash Virtual Machine which declares (allocate memory etc) all the function's variables before function's body execution. So declaring variable somewhere in the function block in ActionScript code just reports compiler to declare variable and it declares at the beginning of the function block at runtime. That's why your code is the same as:

public function foo() : void {
      var a : int = 3;
      a = 0;
 }

The same reason has the compiler warning when you declare some variable twice in the function's body.

Constantiner
  • 14,231
  • 4
  • 27
  • 34
0

For further reference: http://wiki.joa-ebert.com/index.php/Local_Variables