In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice?
var value = 0;
for (var i = 0; i < 100; i++)
{
value = somearray[i];
}
or
for (var i = 0 ; i < 100; i++)
{
var value = somearray[i];
}
There is absolutely no difference in meaning or performance, in JavaScript or ActionScript.
varis a directive for the parser, and not a command executed at run-time. If a particular identifier has been declaredvaronce or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whethervalueis declared to bevarinside the loop, outside the loop, or both.Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it’s better to declare
varin that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associatedvar, and you’ve got yourself an accidental global.In particular:
Crockford will recommend you remove the second
var(or remove bothvars and dovar i;above), and jslint will whinge at you for this. But IMO it’s more maintainable to keep bothvars, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.Personally I tend to declare as
varthe first assignment of a variable in an independent section of code, whether or not there’s another separate usage of the same variable name in some other part of the same function. For me, having to declarevarat all is an undesirable JS wart (it would have been better to have variables default to local); I don’t see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.(*: other than in nested function bodies)