JavaScript For Loop Efficiency – Best Practices

javascript

Is

for (var i=0, cols=columns.length; i<cols; i++) { ... }

more efficient than

for (var i=0; i<columns.length; i++) { ... }

?

In the second variant, is columns.length calculated each time the condition i<columns.length is checked ?

Best Answer

Any expression that's in the second portion of a for will be evaluated once per loop.

So, here, with your second proposition, yes, columns.length will be calculated each time the condition is checked -- which would make the first proposition faster than the second one.


(That's true for many other languages, btw)

Related Question