|
| 1 | +## Array Iteration and Properties |
| 2 | + |
| 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 |
| 5 | +are a number of good reasons **against** the use of `for in` on arrays. |
| 6 | + |
| 7 | +> **Note:** JavaScript arrays are **not** *associative arrays*. JavaScript only |
| 8 | +> has [objects](#object.general) for mapping keys to values. And while associative |
| 9 | +> arrays **preserve** order, objects **do not**. |
| 10 | +
|
| 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 | +[`hasOwnProperty`](#object.hasownproperty), it is already up to **twenty times** |
| 14 | +slower than a normal `for` loop. |
| 15 | + |
| 16 | +### Iteration |
| 17 | + |
| 18 | +In order to achieve the best performance when iterating over arrays, it is best |
| 19 | +to use the classic `for` loop. |
| 20 | + |
| 21 | + var list = [1, 2, 3, 4, 5, ...... 100000000]; |
| 22 | + for(var i = 0, l = list.length; i < l; i++) { |
| 23 | + console.log(list[i]); |
| 24 | + } |
| 25 | + |
| 26 | +There is one extra catch in the above example, which is the caching of the |
| 27 | +length of the array via `l = list.length`. |
| 28 | + |
| 29 | +Although the `length` property is defined on the array itself, there is still an |
| 30 | +overhead for doing the lookup on each iteration of the loop. And while recent |
| 31 | +JavaScript engines **may** apply optimization in this case, there is no way of |
| 32 | +telling whether the code will run on one of these newer engines or not. |
| 33 | + |
| 34 | +In fact, leaving out the caching may result in the loop being only **half as |
| 35 | +fast** as with the cached length. |
| 36 | + |
| 37 | +### The `length` Property |
| 38 | + |
| 39 | +While the *getter* of the `length` property simply returns the number of |
| 40 | +elements that are contained in the array, the *setter* can be used to |
| 41 | +**truncate** the array. |
| 42 | + |
| 43 | + var foo = [1, 2, 3, 4, 5, 6]; |
| 44 | + foo.length = 3; |
| 45 | + foo; // [1, 2, 3] |
| 46 | + |
| 47 | + foo.length = 6; |
| 48 | + foo; // [1, 2, 3] |
| 49 | + |
| 50 | +Assigning a smaller length does truncate the array, but increasing the length |
| 51 | +does not have any effect on the array. |
| 52 | + |
| 53 | +### In Conclusion |
| 54 | + |
| 55 | +For the best performance, it is recommended to always use the plain `for` loop |
| 56 | +and cache the `length` property. The use of `for in` on an array is a sign of |
| 57 | +badly written code that is prone to bugs and bad performance. |
| 58 | + |
0 commit comments