1
1
## Array Iteration and Properties
2
2
3
3
Although 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
5
5
are a number of good reasons ** against** the use of ` for in ` on arrays.
6
6
7
7
> ** Note:** JavaScript arrays are ** not** * associative arrays* . JavaScript only
8
8
> has [ objects] ( #object.general ) for mapping keys to values. And while associative
9
9
> arrays ** preserve** order, objects ** do not** .
10
10
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
13
13
[ ` hasOwnProperty ` ] ( #object.hasownproperty ) , it is already up to ** twenty times**
14
14
slower than a normal ` for ` loop.
15
15
@@ -23,7 +23,7 @@ to use the classic `for` loop.
23
23
console.log(list[i]);
24
24
}
25
25
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
27
27
length of the array via ` l = list.length ` .
28
28
29
29
Although 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.
52
52
53
53
### In Conclusion
54
54
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
56
56
and cache the ` length ` property. The use of ` for in ` on an array is a sign of
57
57
badly written code that is prone to bugs and bad performance.
58
58
0 commit comments