"for" loop and "for/in"
As you might already know, JavaScript is a language that allows you to perform loops, which is where a block of code
is ran over and over again until a certain condition is met; this process is also referred to as "iteration". The most
commonly-used type of loop that most people are used to seeing is a for
loop:
const alphabet = ["a", "b", "c", "d", "e"];
for (let i = 0; i < alphabet.length; i++) {
console.log(alphabet[i]);
}
// a
// b
// c
// d
// e
...this for
loop says, "Initialize i
with a value of 0
. Log a letter from the alphabet
array each iteration; continue doing this until i
is greater than the length of
the array."
A regular for
loop gives you access to the index in the array, but not the actual
element, which is why I retrieved each element by passing in each iteration value as the index. The
for/in
statement works similarly:
const arr = ["a", "b", "c", "d", "e"];
for (let i in arr) {
console.log(i);
}
// 0
// 1
// 2
// 3
// 4
...this loop only gives you access to the index of the current iterable, not the actual element.
"forEach()" and "for/of"
Unlike the for
and for/in
loop,
forEach()
and for/of
actually give you access to the
array element. Additionally, forEach()
also lets you access the index by passing it
as a second argument:
const arr = ["a", "b", "c", "d", "e"];
arr.forEach((letter, i) => {
console.log(`Index ${i} holds letter ${letter}.`);
});
// Index 0 holds letter a.
// Index 1 holds letter b.
// Index 2 holds letter c.
// Index 3 holds letter d.
// Index 4 holds letter e.
...for/of
is similar to forEach()
, except it doesn't
let you access the index...
const arr = ["a", "b", "c", "d", "e"];
for (let letter of arr) {
console.log(letter);
}
// a
// b
// c
// d
// e
...generally, for/of
is the best way to perform iterations. The syntax is much more
concise than a traditional for
loop, making it easier to set up and use. The only downside
to for/of
is that you can't directly access the index, in which case a
regular for
loop will suffice.
Remember, JavaScript is a huge language where there's more than one way to accomplish something, so there's always a different tool for each task. Play around and see what works best.