let array = [1,2,3];
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
For Of
In this chapter we are going to examine how we can loop over arrays, using the methods available to us in the past with ES5 and also the new for-of
looping mechanism in ES6.
For & ForEach
We have a couple of ways of looping through Arrays in ES5 javascript.
For one we have the classic for
loop, like so:
With ES5 Javascript we can also use the forEach
method on the Array class, like so:
let array = [1,2,3];
array.forEach(function (value) {
console.log(value);
});
// 1
// 2
// 3
It’s slightly shorter but has a few downsides:
-
You can’t break out of this loop using a
break
statement or move to the next iteration withcontinue
. -
You can’t return from the enclosing function using a
return
statement.
For In
The for-in
loop is designed for iterating over an objects properties, like so:
var obj = {a:1,b:2};
for (let prop in obj) {
console.log(obj[prop]);
}
// 1
// 2
If we tried to use it with an array, it might initially look like it’s working:
let array = [1,2,3];
for (let value in array) {
console.log(value);
});
// 1
// 2
// 3
But if we tried to print out the type of value
like so:
let array = [1,2,3];
for (let value in array) {
console.log(typeof(value));
};
// string
// string
// string
The value
variable is a string and not a number, using for-in
with arrays converts the value to a string.
If you are expecting a number but in fact have a string this can cause problems, for example "1" + "2"
is the string "12"
and not the number 3
.
For-of loop
Rather than change the way for-in
loops work to better support arrays and in the process create a breaking change, instead in ES6 we have a new syntax called for-of
.
let array = [1,2,3];
for (var value of array) {
console.log(value);
}
// 1
// 2
// 3
-
This is the most concise way of looping through array elements.
-
It avoids all the pitfalls of
for–in
. -
It works with
break
,continue
, andreturn
Summary
The for–in
loop is for looping over object properties.
The for–of
loop is for looping over the values in an array.
for–of
is not just for arrays. It also works on most array-like objects including the new Set
and Map
types which we will cover in the next chapter.