I learned from books that you should write for loop like this:
for(var i=0, len=arr.length; i < len; i++){
// blah blah
}
so the arr.length
will not be calculated each time.
Others say that the compiler will do some optimization to this, so you can just write:
for(var i=0; i < arr.length; i++){
// blah blah
}
I just want to know which is the best way in practice?
It's just 2018 so an update could be nice...
And I really have to disagree with the accepted answer. here is a benchmark on all method http://jsben.ch/mW36e
and sice you can see alot of for-loop like
for(a = 0; ... )
then worth to mention that without 'var' variables will be define globally and this can dramatically affects on speed so it'll get slow.The faster way to loop in an array is by using the filter. The filter() method creates a new array with all elements that pass the test implemented by the provided function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
From my experience, I always prefer filters, map etc..
Another jsperf.com test: http://jsperf.com/while-reverse-vs-for-cached-length
The reverse while loop seems to be the fastest. Only problem is that while (--i) will stop at 0. How can I access array[0] in my loop then?