11## Array Iteration and Properties
22
33Although arrays in JavaScript are objects, there are no good reasons to use
4- the [ ` for in loop ` ] ( #object.forinloop ) in for iteration on them. In fact there
4+ the [ ` for in loop ` ] ( #object.forinloop ) in for iteration on them. In fact, there
55are a number of good reasons ** against** the use of ` for in ` on arrays.
66
77> ** Note:** JavaScript arrays are ** not** * associative arrays* . JavaScript only
88> has [ objects] ( #object.general ) for mapping keys to values. And while associative
99> arrays ** preserve** order, objects ** do not** .
1010
11- Since the ` for in ` loop enumerates all the properties that are on the prototype
12- chain and the only way to exclude those properties is to use
11+ Because the ` for in ` loop enumerates all the properties that are on the prototype
12+ chain and because the only way to exclude those properties is to use
1313[ ` hasOwnProperty ` ] ( #object.hasownproperty ) , it is already up to ** twenty times**
1414slower than a normal ` for ` loop.
1515
@@ -23,7 +23,7 @@ to use the classic `for` loop.
2323 console.log(list[i]);
2424 }
2525
26- There is one extra catch in the above example, that is the caching of the
26+ There is one extra catch in the above example, which is the caching of the
2727length of the array via ` l = list.length ` .
2828
2929Although the ` length ` property is defined on the array itself, there is still an
@@ -52,7 +52,7 @@ does not have any effect on the array.
5252
5353### In Conclusion
5454
55- For the best performance it is recommended to always use the plain ` for ` loop
55+ For the best performance, it is recommended to always use the plain ` for ` loop
5656and cache the ` length ` property. The use of ` for in ` on an array is a sign of
5757badly written code that is prone to bugs and bad performance.
5858
0 commit comments