Lesson 22 +15 XP

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...of gives you the values.
  • for...in gives you the keys/indexes.

Use for...of for arrays and strings. Use for...in for objects.

TL;DR

  • for...of loops over values.
  • for...in loops over keys/indexes.
  • Use for...of for arrays and strings.
  • Use for...in for object properties.