Loading lessons...
For Of and For In
For Of and For In
JavaScript has two modern loops for collections: for...of and for...in.
for...of (values)
for...of loops through the values of arrays and strings:
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
This prints each fruit name.
Works on strings too
for (let letter of "Hi") {
console.log(letter);
}
This prints H, then i.
for...in (keys or indexes)
for...in loops through the keys (property names) of objects:
let person = { name: "Ada", age: 36 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
The key difference
for...ofgives you the values.for...ingives you the keys/indexes.
Use for...of for arrays and strings. Use for...in for objects.
TL;DR
for...ofloops over values.for...inloops over keys/indexes.- Use for...of for arrays and strings.
- Use for...in for object properties.