Difficulty: Beginner
Loops allow you to execute a block of code repeatedly until a condition is met. They are fundamental to programming - almost every program needs to process collections of data, repeat operations, or iterate until a goal is achieved. JavaScript provides several loop constructs, each suited to different use cases.
The classic for loop has three parts: initialization (runs once before the loop starts), condition (checked before each iteration), and update (runs after each iteration). It is the most versatile loop and is ideal when you know in advance how many times you need to iterate, such as processing array elements by index. The while loop is simpler - it only has a condition and keeps looping as long as that condition is truthy. Use while when you don't know how many iterations you'll need, such as reading data until a sentinel value is reached.
The do-while loop is similar to while but guarantees at least one execution because the condition is checked after the loop body runs, not before. This is useful for menus, prompts, or any scenario where you need to execute the body before deciding whether to continue. In practice, do-while is the least commonly used loop in JavaScript, but it's important to know it exists.
The for...in loop iterates over the enumerable property names (keys) of an object. It is designed for objects, not arrays. When used on arrays, for...in iterates over index strings ('0', '1', '2'), which can cause unexpected behavior because it also iterates over inherited enumerable properties from the prototype chain. The for...of loop, introduced in ES6, iterates over the values of any iterable object - arrays, strings, Maps, Sets, NodeLists, and any object that implements the iterable protocol. For arrays, for...of is almost always the right choice.
The break statement immediately exits the current loop entirely, while continue skips the rest of the current iteration and moves to the next one. JavaScript also supports labeled statements, which allow break and continue to target a specific outer loop in nested loop structures. While labeled loops are rarely needed, they solve the problem of breaking out of deeply nested loops without using flag variables.
Regarding performance, all loop types have similar performance characteristics in modern JavaScript engines. The for loop with cached length (const len = arr.length) was once faster, but modern engines optimize this automatically. Choose the loop type that makes your code most readable - for...of for arrays, for...in for objects, and the classic for loop when you need the index.
// Classic for loop
console.log("for loop:");
for (let i = 0; i < 5; i++) {
process.stdout.write(`${i} `);
}
console.log();
// while loop
console.log("while loop:");
let count = 5;
while (count > 0) {
process.stdout.write(`${count} `);
count--;
}
console.log();
// do-while (runs at least once)
console.log("do-while:");
let num = 0;
do {
console.log(`num is ${num}`);
num += 5;
} while (num < 3);
// Looping backward
console.log("Backward:");
for (let i = 4; i >= 0; i--) {
process.stdout.write(`${i} `);
}
console.log();
The for loop is best when you know the iteration count. while is best when the count depends on a dynamic condition. do-while runs the body first, then checks - notice it prints 'num is 0' even though 0 is not less than 3.
// for...in iterates over object KEYS
const person = { name: "Alice", age: 25, city: "NYC" };
console.log("for...in (object keys):");
for (const key in person) {
console.log(` ${key}: ${person[key]}`);
}
// for...of iterates over iterable VALUES
const fruits = ["apple", "banana", "cherry"];
console.log("for...of (array values):");
for (const fruit of fruits) {
console.log(` ${fruit}`);
}
// for...of with strings
console.log("for...of (string characters):");
for (const char of "Hello") {
process.stdout.write(`${char} `);
}
console.log();
// for...of with entries (index + value)
console.log("entries():");
for (const [index, value] of fruits.entries()) {
console.log(` ${index}: ${value}`);
}
for...in gives you property keys (strings) and is designed for objects. for...of gives you values and works with any iterable (arrays, strings, Maps, Sets). Use array.entries() with for...of when you need both the index and the value.
// break exits the loop entirely
console.log("break example:");
for (let i = 0; i < 10; i++) {
if (i === 5) break;
process.stdout.write(`${i} `);
}
console.log();
// continue skips current iteration
console.log("continue (skip evens):");
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue;
process.stdout.write(`${i} `);
}
console.log();
// Labeled loop - break outer from inner
console.log("Labeled break:");
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) break outer;
console.log(` i=${i}, j=${j}`);
}
}
break stops the loop completely. continue jumps to the next iteration. Labeled statements (outer:) allow you to break or continue a specific loop in nested structures - useful for search algorithms where you need to exit multiple levels at once.
// Searching for an element
const numbers = [10, 25, 30, 45, 50];
let found = null;
for (const num of numbers) {
if (num > 28) {
found = num;
break; // Stop at first match
}
}
console.log(`First number > 28: ${found}`);
// Accumulating a total
const prices = [9.99, 24.50, 3.75, 15.00];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(`Total: ${total.toFixed(2)}`);
// Building a new array (loop version)
const names = ["alice", "bob", "charlie"];
const capitalized = [];
for (const name of names) {
capitalized.push(name[0].toUpperCase() + name.slice(1));
}
console.log(capitalized);
// Iterating object entries
const scores = { math: 92, science: 88, english: 95 };
for (const [subject, score] of Object.entries(scores)) {
console.log(`${subject}: ${score >= 90 ? "A" : "B"}`);
}
These patterns show real-world loop usage: searching with early exit, accumulating values, transforming collections, and iterating objects. Note: many of these can also be done with array methods like find(), reduce(), and map() - which you'll learn in later lessons.
for Loop, while Loop, do-while Loop, for...in, for...of, break/continue