Which style is better practice for performance in Javascript?
Style1
var x = ''
for(var i = 0 ; i < arr.length ; i ++){
x = ....
//do something with x
}
Style2
for(var i = 0 ; i < arr.length ; i ++){
var x = ....
//do something with x
}
JavaScript doesn’t have block scope like some other languages, only function scope. This means that in practice the JS engine interprets the first version of your code as:
And the second version exactly the same except without assigning a default
''value tox:So in my opinion “Style 1” is bad practice because you assign a value that is never used. But I think “Style 2” is worse because it implies block scope that doesn’t exist.
As for which performs better, without testing it I’d expect both to be pretty much the same with any modern JS engine.