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?
While loop is a bit faster than for loop.
Use while loop instead
i++ is faster than ++i, --i and i--
Also, you can save the last line doing arr[i++] the last time you need to access i (but this can be hard to debug).
You can test it here (with other loop tests): http://jsperf.com/for-vs-whilepop/5
The most elegant solution I know of is using map.
As of June 2016, doing some tests in latest Chrome (71% of the browser market in May 2016, and increasing):
I believe this thread is too old and it is misleading programmers to think they need to cache length, or use reverse traversing whiles with decrements to achieve better performance, writing code that is less legible and more prone to errors than a simple straightforward for loop. Therefore, I recommend:
If your app iterates over a lot of items or your loop code is inside a function that is used often, a straightforward for loop is the answer:
If your app doesn't really iterate through lots of items or you just need to do small iterations here and there, using the standard forEach callback or any similar function from your JS library of choice might be more understandable and less prone to errors, since index variable scope is closed and you don't need to use brackets, accessing the array value directly:
If you really need to scratch a few milliseconds while iterating over billions of rows and the length of your array doesn't change through the process, you might consider caching the length in your for loop. Although I think this is really not necessary nowadays:
A basic while loop is often the fastest. jsperf.com is a great sandbox to test these types of concepts.
https://jsperf.com/fastest-array-loops-in-javascript/24
"Best" as in pure performance? or performance AND readability?
Pure performance "best" is this, which uses a cache and the ++prefix operator (my data: http://jsperf.com/caching-array-length/189)
I would argue that the cache-less for-loop is the best balance in execution time and programmer reading time. Every programmer that started with C/C++/Java won't waste a ms having to read through this one