A traditional for loop gives you both the index (position) and the value.
for (let i = 0; i < array.length; i++) {
// code runs for each index
}
let i = 0 - start counter at 0 i < array.length - continue while i is less than array length i++ - add 1 to i after each iteration const numbers = [10, 20, 30];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
// sum is 60
for...of can get you an index too — you just have to track it yourself:
const fruits = ["apple", "banana", "cherry"];
let i = 0;
for (const fruit of fruits) {
const positioned = i + ": " + fruit;
i = i + 1;
}
for-i gets the same result, but the counter lives in the loop header instead of lines you
manage by hand:
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
const positioned = i + ": " + fruits[i];
}
Use for-of when you just need each value. Use for-i when you need: