for-of
is a new loop in ES6 that replaces both for-in
and forEach()
and supports the new iteration protocol.
Syntax
for (variable of iterable) {
statement
}
Iterating over an Array
let values = [10, 20, 30];
for (let value of values) {
console.log(value);
}
// 10
// 20
Iterating over a String
let color = "red";
for (let c of color) {
console.log(c);
}
// r
// e
// d
Difference between for...of
and for...in
The for...in
loop will iterate over all enumerable properties of an object.
The for...of
syntax is specific to collections, rather than all objects.
The following example shows the difference between a for...of
loop and a for...in
loop.
for...in
Example
var values = ["one", "two"];
for (var value in values) {
console.log("Index is: "+value);
}
// Index is: 0
// Index is: 1
for (var value in values) {
console.log("Value is: "+values[value]);
}
// Value is: one
// Value is: two
for...of
Example
var values = ["one", "two"];
for (let value of values) {
console.log("Value is: "+value);
}
// Value is: one
// Value is: two