JavaScript: loops
Loops repeat a block of code while a condition holds or while items remain in a collection.
What you will learn
- How
for,while, andfor...ofdiffer - How to traverse an array without an off-by-one error
- How
breakandcontinuechange a loop
Minimal examples
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
for (let i = 0; i < 3; i++) {
console.log(i);
}Use for...of when you need each value. Use a counted for loop when the index or a precise number of iterations matters.
Common mistakes
- Ensure the loop condition eventually becomes false; otherwise the loop never ends.
- Use
i < array.lengthrather thani <= array.lengthfor zero-based indexes. - Do not use
for...inas the default way to read array values; it iterates property names.