🌱BeginnerControl Flow

Loops

for, while, for...of, and for...in repeating actions efficiently.

Overview

Loops execute a block of code repeatedly. JavaScript has several loop constructs, each suited to different scenarios. The classic for loop is best when you need the index or need to iterate a precise number of times. The while loop runs while a condition is true useful when you don't know the count in advance. for...of iterates over the values of any iterable (arrays, strings, Sets, Maps) it's the cleanest way to iterate an array. for...in iterates over the enumerable property keys of an object. Choose the loop that best expresses intent. When iterating an array's values, for...of reads more clearly than for with index. When you need the index, a for loop or array.forEach() with an index parameter is clearer. break exits a loop early; continue skips to the next iteration.

Key Points

  • •for loop: best when you need the index or the exact number of iterations
  • •while loop: best when the exit condition depends on runtime data
  • •for...of: cleanest way to iterate values in an array, string, Set, or Map
  • •for...in: iterates an object's own enumerable property names avoid for arrays
  • •break exits the loop immediately; continue jumps to the next iteration
  • •Avoid infinite loops: always ensure the loop condition eventually becomes false

Examples

for, while, for...of side by side

const fruits = ["apple", "banana", "cherry"];

// Classic for
for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}

// for...of (values only)
for (const fruit of fruits) {
  console.log(fruit);
}

// while
let i = 0;
while (i < fruits.length) {
  console.log(fruits[i]);
  i++;
}

for...in for object keys

const person = { name: "Alice", age: 30, city: "Paris" };

for (const key in person) {
  console.log(key, ":", person[key]);
}
// name : Alice
// age : 30
// city : Paris

for...in is designed for plain objects. For arrays use for...of or forEach.

break and continue

// break stop early
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0 1 2 3 4
}

// continue skip even numbers
for (let i = 0; i < 6; i++) {
  if (i % 2 === 0) continue;
  console.log(i); // 1 3 5
}

Common Mistakes

  • Off-by-one errors: i < array.length (correct) vs i <= array.length (goes one too far)
  • Using for...in on arrays it iterates indices as strings and may include prototype properties
  • Modifying the array while iterating it with a for loop causes skipped or repeated elements

Note

In modern JavaScript, for...of and array methods like forEach, map, and filter are preferred over classic for loops for arrays. They express intent more clearly and are harder to get wrong.

Exercises

Write JavaScript code to solve each exercise. Run it and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

Which loop is best for iterating the values of an array in modern JavaScript?