Link Search Menu Expand Document

Loop Da Loop

Thereโ€™s more to looping in Javascript than the standard for and while loops. The for of syntax and the forEach function are two ways to automatically โ€œvisitโ€ every element in a collection of data.

Table of Contents

  1. For Of Enumeration
  2. forEach Callback Loop
  3. Longer forEach Callbacks
  4. Looping Over Object Key/Value Pairs

For Of Enumeration

Beyond the standard for loop, there are two other popular ways to loop through Arrays in Javascript.

The for of loop assigns each element in turn a loop variable:

let fruitBasket = ["๐ŸŽ", "๐Ÿ“", "๐Ÿ’", "๐Ÿฅ"];

// for-of: Concise loop when you don't need the index value.

for (const fruit of fruitBasket) {
  console.log(fruit);
}

The fruit variable is scoped to the curly-braced code block.

โ˜‘๏ธ Best Practice: Define your loop variables as const to prevent accidental modification of array elements.

forEach Callback Loop

The array forEach method passes each element in turn as an argument to a provided callback:

// Print every element using an arrow function:

fruitBasket.forEach((fruit) => console.log(fruit));

// With forEach you can also get access to the index:

fruitBasket.forEach((fruit, i) => console.log(`${i}: ${fruit}`));

// 0: ๐ŸŽ
// 1: ๐Ÿ“
// 2: ๐Ÿ’
// 3: ๐Ÿฅ

Longer forEach Callbacks

Longer forEach callbacks are also possible.

Letโ€™s build a fruit pyramid:

fruitBasket.forEach((fruit, i) => {
  let length = fruitBasket.length;
  let row = " ".repeat(length - i) + fruit.repeat(i + 1);
  console.log(row);
});

//    ๐ŸŽ
//   ๐Ÿ“๐Ÿ“
//  ๐Ÿ’๐Ÿ’๐Ÿ’
// ๐Ÿฅ๐Ÿฅ๐Ÿฅ๐Ÿฅ

Looping Over Object Key/Value Pairs

We can access object values by way of keys:

const games = { soccer: "โšฝ", baseball: `โšพ` };

// Bracket notation using a string index:
console.log(games["soccer"]);

// Dot notation using a period:
console.log(games.baseball);

We can loop over an objectโ€™s key/value pairs using the Object.entries method.

for (const [game, ball] of Object.entries(games)) {
  console.log(`We use a ${ball} to play ${game}.`);
}

// We use a โšฝ to play soccer.
// We use a โšพ to play baseball.

This works because Object.entries(games) returns an array of arrays:

[
  ["soccer", "โšฝ"],
  ["baseball", "โšพ"],
];

Weโ€™ll learn other similar techniques in the โ€œDestructuringโ€ section of this module.