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
- For Of Enumeration
- forEach Callback Loop
- Longer forEach Callbacks
- 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.