Is the second better than the first?
FIRST:
var count:int=myArray.length;
for(var i:uint=0;i<count;i++)
{
var str:String=myArray[i].label;
var somethingElse:Class=...;
var andAnotherThing:MyInstance=new MyInstance(somethingElse);
...
}
SECOND:
var count:int=myArray.length;
var str:String;
var somethingElse:Class;
var andAnotherThing:MyInstance;
for(var i:uint=0;i<count;i++)
{
str=myArray[i].label;
somethingElse=...;
andAnotherThing=new MyInstance(somethingElse);
...
}
Thank you.
If the variable is declared outside the loop, then it has the global scope as it can be used through-out the function and inside of the loop too. If the variable is declared inside the loop, then the scope is only valid inside the loop and if used outside the loop will give an error.
As per Hubspot's documentation, any variables defined within loops are limited to the scope of that loop and cannot be called from outside of the loop.
It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs.
If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.
In Actionscript and Javascript, variables are scoped to the function, not the block. It's called variable hoisting.
ActionScript 3.0 Variables
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.
So effectively your code will behave like this regardless of where you declare your variables within the function:
var count:int;
var str:String;
var i:uint;
var somethingElse:Class;
var andAnotherThing:MyInstance;
count = myArray.length;
for(i=0;i<count;i++)
{
str=myArray[i].label;
somethingElse = ...;
andAnotherThing = new MyInstance(somethingElse);
...
}
Nevertheless, I still prefer to declare my variables within the blocks that use them primarily for maintenance reasons and general clarity.
On Flash, the answer is it doesn't matter. Flash is weird when it comes to variable declaration. Do the following and see what happens:
for(var i:uint=0;i<count;i++)
{
var str:String=myArray[i].label;
var somethingElse:Class=...;
var andAnotherThing:MyInstance=new MyInstance(somethingElse);
}
var str:String=myArray[i].label;
Even though str ran out of scope out of the for loop, you will get a variable redefinition warning, meaning that the variable will only be "initialized" once in a for loop;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With