Skip to main content
๐Ÿงฑbeginner

Loops

for, while, for...of, for...in โ€” repeat code efficiently without writing it multiple times.

Why Loops?

Loops let you repeat a block of code without copy-pasting. Instead of:

hljs javascript
console.log("Item 1");
console.log("Item 2");
console.log("Item 3");
// ...100 more lines

You write:

hljs javascript
for (let i = 1; i <= 100; i++) {
  console.log("Item " + i);
}

The for Loop

The classic loop, ideal when you know how many iterations you need:

hljs javascript
for (let i = 0; i < 5; i++) {
  console.log(i); // 0, 1, 2, 3, 4
}

// Three parts: initialization; condition; update
// for (init; condition; update) { body }

// Count backwards
for (let i = 5; i > 0; i--) {
  console.log(i); // 5, 4, 3, 2, 1
}

// Step by 2
for (let i = 0; i <= 10; i += 2) {
  console.log(i); // 0, 2, 4, 6, 8, 10
}

Iterating over arrays:

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

for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}
// 0 "apple"
// 1 "banana"
// 2 "cherry"

The while Loop

Runs as long as a condition is true. Use when you don't know the iteration count upfront:

hljs javascript
let attempts = 0;
let password = "";

while (password !== "secret") {
  attempts++;
  password = attempts === 3 ? "secret" : "wrong"; // simulating input
  console.log("Attempt #" + attempts);
}
console.log("Access granted after " + attempts + " attempts!");

// Countdown
let count = 5;
while (count > 0) {
  console.log(count--);
}
console.log("Liftoff! ๐Ÿš€");

โš ๏ธBeware infinite loops

If the condition never becomes false, your program hangs. Always make sure something inside the loop moves toward the termination condition:

hljs javascript
// โœ— Infinite loop โ€” don't run this!
while (true) {
  console.log("help");
  // no exit condition!
}

// โœ“ Has an exit
let x = 0;
while (x < 3) {
  console.log(x);
  x++; // this will eventually make x >= 3
}

do...while Loop

Like while, but guarantees at least one execution:

hljs javascript
let userInput;

do {
  // imagine getting user input here
  userInput = "valid"; // simulate input
  console.log("Processing input:", userInput);
} while (userInput === "retry");
// Body runs at least once, then checks the condition

for...of โ€” Iterate Values

The modern way to loop over iterables (arrays, strings, Maps, Sets):

hljs javascript
const colors = ["red", "green", "blue"];

for (const color of colors) {
  console.log(color);
}
// red, green, blue

// Works on strings too
for (const char of "hello") {
  console.log(char); // h, e, l, l, o
}

// With index (using entries())
for (const [index, color] of colors.entries()) {
  console.log(index, color);
}
// 0 "red", 1 "green", 2 "blue"

โœ…Tip

Prefer for...of over the classic for loop when you just need the values and don't care about the index. It's cleaner and works with any iterable.

for...in โ€” Iterate Object Keys

Iterates over the enumerable property keys of an object:

hljs javascript
const person = { name: "Alice", age: 30, city: "NYC" };

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

โš ๏ธDon't use for...in on arrays

for...in iterates over all enumerable properties, including any added to Array.prototype. Use for...of or .forEach() for arrays.

hljs javascript
const arr = [1, 2, 3];
Array.prototype.extra = "oops";

for (const key in arr) {
  console.log(key); // "0", "1", "2", "extra" โ€” problem!
}

break and continue

Control loop execution mid-iteration:

hljs javascript
// break โ€” exit the loop immediately
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i); // 0, 1, 2, 3, 4
}

// continue โ€” skip this iteration, go to next
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue; // skip even numbers
  console.log(i); // 1, 3, 5, 7, 9
}

Labeled loops (for nested break/continue):

hljs javascript
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) break outer; // breaks the outer loop
    console.log(i, j);
  }
}
// 0 0, 0 1, 0 2, 1 0 โ€” then stops

Array Methods as Loops

Modern JavaScript often prefers array methods over explicit loops:

hljs javascript
const nums = [1, 2, 3, 4, 5];

// forEach โ€” runs a function for each element
nums.forEach((n, i) => console.log(i, n));

// map โ€” transforms each element, returns new array
const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10]

// filter โ€” keeps elements that pass a test
const evens = nums.filter(n => n % 2 === 0); // [2, 4]

// reduce โ€” accumulates to a single value
const sum = nums.reduce((acc, n) => acc + n, 0); // 15

// find โ€” first element that passes
const found = nums.find(n => n > 3); // 4

// some โ€” true if at least one passes
const hasEven = nums.some(n => n % 2 === 0); // true

// every โ€” true if all pass
const allPositive = nums.every(n => n > 0); // true
โ–ถTry it yourself

Key Takeaways

  • for โ€” when you know the iteration count
  • while โ€” when you don't know the count upfront
  • for...of โ€” modern way to iterate over array values
  • for...in โ€” iterate over object keys (don't use on arrays)
  • break exits the loop; continue skips to the next iteration
  • Array methods (.map(), .filter(), .forEach()) are often cleaner than explicit loops

Ready to test your knowledge?

Take a quiz on what you just learned.

Take the Quiz โ†’