Javascript for loop without recalculating array’s length

In my Javascript reference book, for loops are optimized in the following way:

for( var i = 0, len = keys.length; i < len; i + +) { BODY }

Apparently, doing “len = keys.length” prevents the computer from recalculating keys.length each time it goes through the for loop.

I don’t understand why the book doesn’t write “var len = keys.length” instead of “len = keys.length”? Isn’t the book making “len” a global variable, which isn’t good if you’re trying to nest two for-loops that loop through two arrays?


for( var i = 0, len = keys.length; i < len; i + +) { 
     for (var i = 0; len = array2.length; i < len; i++) {

Source: Flanagan, David (2011-04-18). JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides) (Kindle Locations 6992-6998). O’Reilly Media. Kindle Edition.

Source: syntax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.