If you are developer then you must know that looping array is a common code practice and frequently used in code. Every web developers must be expert in different kind of the loop through all the entries in an array.
Below are some most used code practice for looping arrays.
- a
for-of
loop (ES2015+ only) Array#forEach
(or its relativessome
and such) (ES5+ only)- a simple old-fashioned
for
loop - or
for-in
with safeguards
1. Using forEach
: accepts a callback function, and, optionally, a value to use as this
when calling that callback (not used above). The callback is called for each entry in the array.
forEach
has the benefit that you don’t have to declare indexing and value variables in the containing scope, as they’re supplied as arguments to the iteration function, and so nicely scoped to just that iteration.
var posts = ["a", "b", "c"];
posts.forEach(function(post) {
console.log(post);
});
Additionally, forEach
is the “loop through them all” function, but ES5 defined several other useful “work your way through the array and do things” functions, including
- every (stops looping the first time the callback returns false or something falsey)
- some (stops looping the first time the callback returns true or something truthy)
- filter (creates a new array including elements where the filter function returns true and omitting the ones where it returns false)
- map (creates a new array from the values returned by the callback)
- reduce (builds up a value by repeatedly calling the callback, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
- reduceRight (like reduce, but works in descending rather than ascending order)
2. Using simple for
loop: old method
var index;
var posts = ["a", "b", "c"];
for (index = 0; index < posts.length; ++index) {
console.log(posts[index]);
}
If the length of the array won’t change during the loop, and it’s in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a tiny bit faster.
//faster than above
var index, len;
var posts = ["a", "b", "c"];
for (index = 0, len = posts.length; index < len; ++index) {
console.log(posts[index]);
}
3. Using for-in
: for-in
loops through the enumerable properties of an object, not the indexes of an array. The order is not guaranteed, not even in ES2015 (ES6).
Real use cases for for-in
on an array are: It’s a sparse arrays with massive gaps in it, or You’re using non-element properties and you want to include them in the loop.
// `a` is a sparse array
var key;
var a = [];
a[0] = "a";
a[10] = "b";
a[10000] = "c";
for (key in a) {
if (a.hasOwnProperty(key) &&
/^0$|^[1-9]\d*$/.test(key) &&
key <= 4294967294
) {
console.log(a[key]);
}
}
4. Using for-of
:
const posts = ["a", "b", "c"];
for (const val of posts) {
console.log(val);
}