When working with arrays, you sometimes want to execute code for each value in the array. This is called iterating or looping over the array.
Here we will look at the case where you do not want to modify the array in the process. For transforming arrays, see Concept Array Transformations instead.
The most basic to iterate over an array is to use a for loop, see Concept For Loops.
const numbers = [6.0221515, 10, 23];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// => 6.0221515
// => 10
// => 23When you want to work with the value directly in each iteration and do not require the index at all, you can use a for .. of loop.
for...of works like the basic for loop shown above, but instead of having to deal with the index as variable in the loop, you are provided directly with the value.
const numbers = [6.0221515, 10, 23];
// Because re-assigning number inside the loop will be very
// confusing, disallowing that via const is preferable.
for (const number of numbers) {
console.log(number);
}
// => 6.0221515
// => 10
// => 23Just like in regular for loops, you can use continue stop the current iteration and break to stop the execution of the loop entirely.
Every array includes a forEach method that can also be used to loop over it.
forEach accepts a callback as parameter.
The callback function is called once for each element in the array.
The current element, its index and the full array are provided to the callback as arguments.
Often, only the first or the first two are used.
const numbers = [6.0221515, 10, 23];
numbers.forEach((number, index) => console.log(number, index));
// => 6.0221515 0
// => 10 1
// => 23 2There is no way to stop the iteration once the forEach loop was started.
The statements break and continue do not exist it this context.