DevPath · Learn to code ESPTEN

Loops

for...of, for...in, break and continue

Iterating over collections

Most of the time you don't want to count bare numbers, but to go through the elements of a list: the products in a cart, the names in a group, the letters in a word. For that there are versions of for that are far more convenient, and read almost like a sentence.

for...of: iterates over the values

Ideal for arrays and strings. On each round it gives you the element directly:

const fruits = ["apple", "pear", "grape"];
for (const fruit of fruits) {
  console.log(fruit);
}
// "apple", "pear", "grape"

It also works with strings, character by character:

for (const letter of "abc") {
  console.log(letter); // "a", "b", "c"
}

for...in: iterates over the keys/indices

Meant for objects, where it gives you the name of each property:

const person = { name: "Ana", age: 25 };
for (const key of person) {} // ❌ this does NOT work
for (const key in person) {
  console.log(key, "=>", person[key]);
}
// "name => Ana", "age => 25"

Trick to not get confused: of means "give me the values" of arrays/strings; in means "give me the keys" of objects. If you mix them up, no worries: even veterans second-guess this one sometimes.

Controlling the flow: break and continue

for (let i = 1; i <= 10; i++) {
  if (i === 5) break;     // when reaching 5, stop entirely
  if (i % 2 === 0) continue; // ignore even numbers
  console.log(i);          // prints 1, 3
}

Examples

Iterate over an array with for...of

const colors = ["red", "green", "blue"];
for (const color of colors) {
  console.log(color.toUpperCase());
}

Skip and stop with continue and break

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) continue; // skip even numbers
  if (i > 5) break;          // when reaching 7, stop entirely
  console.log(i);            // prints 1, 3, 5
}
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← while and do...whileView the module →