Loops
Loops allow you to repeat code multiple times without writing the same code over and over. They’re fundamental for processing lists, repeating tasks, and building efficient programs.
What are Loops?
A loop executes a block of code repeatedly until a condition is met:
// Without loop (repetitive)
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
// With loop (efficient)
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
JavaScript has several types of loops:
for- when you know how many times to loopwhile- when you loop until a condition changesdo...while- like while, but runs at least oncefor...of- for iterating arraysfor...in- for iterating object properties
for Loop
The most common loop, perfect when you know how many iterations you need:
Basic Syntax
for (initialization; condition; increment) {
// Code to repeat
}
Example
for (let i = 0; i < 5; i++) {
console.log('Iteration:', i);
}
// Output:
// Iteration: 0
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4
How it works:
- Initialization (
let i = 0) - runs once at the start - Condition (
i < 5) - checked before each iteration - Code block - executes if condition is true
- Increment (
i++) - runs after each iteration - Repeat from step 2
Counting Examples
// Count up
for (let i = 1; i <= 10; i++) {
console.log(i);
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
// Count down
for (let i = 10; i >= 1; i--) {
console.log(i);
}
// 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
// Count by 2
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}
// 0, 2, 4, 6, 8, 10
Looping Through Arrays
const fruits = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// apple
// banana
// orange
Common pattern:
const numbers = [10, 20, 30, 40, 50];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log('Total:', sum); // Total: 150
while Loop
Repeats while a condition is true. Use when you don’t know the number of iterations in advance:
Basic Syntax
while (condition) {
// Code to repeat
}
Example
let count = 0;
while (count < 5) {
console.log('Count:', count);
count++;
}
// Output:
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4
Important: Make sure the condition eventually becomes false, or you’ll have an infinite loop!
Practical Examples
// User input validation (conceptual)
let password = '';
while (password.length < 8) {
// password = prompt('Enter password (min 8 characters):');
password = 'shortpwd'; // Example
console.log('Password too short');
break; // Break to prevent infinite loop in this example
}
// Countdown
let countdown = 5;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
console.log('Blast off!');
// 5, 4, 3, 2, 1, Blast off!
// Processing until empty
const tasks = ['task1', 'task2', 'task3'];
while (tasks.length > 0) {
const task = tasks.pop();
console.log('Processing:', task);
}
// Processing: task3
// Processing: task2
// Processing: task1
do…while Loop
Like while, but always executes at least once:
Syntax
do {
// Code to repeat
} while (condition);
Example
let i = 0;
do {
console.log('Count:', i);
i++;
} while (i < 5);
// Output: Count: 0, 1, 2, 3, 4
Difference from while
// while - may not run at all
let x = 10;
while (x < 5) {
console.log('This never runs');
}
// do...while - runs at least once
let y = 10;
do {
console.log('This runs once');
} while (y < 5);
// Output: This runs once
Practical Use Case
// Menu system that must show at least once
let choice;
do {
console.log('1. Start Game');
console.log('2. Settings');
console.log('3. Exit');
// choice = getUserChoice();
choice = 3; // Example
} while (choice !== 3);
console.log('Exiting...');
for…of Loop
Modern loop for iterating over arrays (and other iterables):
Syntax
for (const item of array) {
// Use item
}
Example
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// Output: red, green, blue
Much cleaner than traditional for loop:
// Traditional for loop
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// for...of loop (simpler!)
for (const color of colors) {
console.log(color);
}
Practical Examples
// Processing items
const prices = [9.99, 14.99, 19.99];
for (const price of prices) {
console.log('$' + price);
}
// String iteration (strings are iterable!)
const word = 'hello';
for (const letter of word) {
console.log(letter);
}
// h, e, l, l, o
// Calculate total
const cart = [29.99, 49.99, 9.99];
let total = 0;
for (const price of cart) {
total += price;
}
console.log('Total: $' + total); // Total: $89.97
for…in Loop
Iterates over object properties (keys):
Syntax
for (const key in object) {
// Use key
}
Example
const person = {
name: 'Alice',
age: 25,
city: 'New York'
};
for (const key in person) {
console.log(key + ':', person[key]);
}
// Output:
// name: Alice
// age: 25
// city: New York
Array Indices (not recommended)
const fruits = ['apple', 'banana', 'orange'];
// for...in gives indices (not recommended for arrays)
for (const index in fruits) {
console.log(index, fruits[index]);
}
// 0 apple, 1 banana, 2 orange
// Use for...of for arrays instead
for (const fruit of fruits) {
console.log(fruit);
}
break Statement
Exits a loop immediately:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop when i is 5
}
console.log(i);
}
// Output: 0, 1, 2, 3, 4
Practical Example: Finding an Item
const numbers = [3, 7, 12, 5, 19, 8];
let found = false;
for (const num of numbers) {
if (num > 10) {
console.log('Found number greater than 10:', num);
found = true;
break; // Stop searching
}
}
if (!found) {
console.log('No number greater than 10');
}
// Output: Found number greater than 10: 12
continue Statement
Skips the current iteration and continues to the next:
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skip when i is 2
}
console.log(i);
}
// Output: 0, 1, 3, 4 (skips 2)
Practical Example: Filtering
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log('Even numbers:');
for (const num of numbers) {
if (num % 2 !== 0) {
continue; // Skip odd numbers
}
console.log(num);
}
// Output: 2, 4, 6, 8, 10
Nested Loops
Loops inside loops:
// Multiplication table
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} x ${j} = ${i * j}`);
}
}
// Output:
// 1 x 1 = 1
// 1 x 2 = 2
// 1 x 3 = 3
// 2 x 1 = 2
// 2 x 2 = 4
// ...
2D Array Example
const grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
console.log(`[${row}][${col}] = ${grid[row][col]}`);
}
}
Common Patterns
1. Sum of Array
const numbers = [10, 20, 30, 40, 50];
let sum = 0;
for (const num of numbers) {
sum += num;
}
console.log('Sum:', sum); // Sum: 150
2. Find Maximum
const scores = [85, 92, 78, 95, 88];
let max = scores[0];
for (const score of scores) {
if (score > max) {
max = score;
}
}
console.log('Highest score:', max); // 95
3. Count Occurrences
const votes = ['red', 'blue', 'red', 'green', 'red', 'blue'];
let redCount = 0;
for (const vote of votes) {
if (vote === 'red') {
redCount++;
}
}
console.log('Red votes:', redCount); // 3
4. Build a String
const words = ['Hello', 'World', 'from', 'JavaScript'];
let sentence = '';
for (let i = 0; i < words.length; i++) {
sentence += words[i];
if (i < words.length - 1) {
sentence += ' ';
}
}
console.log(sentence); // Hello World from JavaScript
5. Filter Array (Create New Array)
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = [];
for (const num of numbers) {
if (num % 2 === 0) {
evenNumbers.push(num);
}
}
console.log(evenNumbers); // [2, 4, 6, 8, 10]
6. Reverse Array
const original = [1, 2, 3, 4, 5];
const reversed = [];
for (let i = original.length - 1; i >= 0; i--) {
reversed.push(original[i]);
}
console.log(reversed); // [5, 4, 3, 2, 1]
Loop Performance Tips
// ❌ Bad - recalculates length each iteration
for (let i = 0; i < array.length; i++) {
// ...
}
// ✅ Better - cache length
const len = array.length;
for (let i = 0; i < len; i++) {
// ...
}
// ✅ Best - use for...of when you don't need index
for (const item of array) {
// ...
}
Best Practices
✅ DO:
- Use
for...offor arrays when you don’t need the index - Use meaningful variable names (
for (const user of users)) - Cache array length in performance-critical loops
- Use
breakto exit early when possible - Keep loop bodies simple and readable
// Good
for (const product of products) {
console.log(product.name);
}
// Good - clear purpose
for (let i = 0; i < 10; i++) {
console.log(`Iteration ${i + 1} of 10`);
}
❌ DON’T:
- Create infinite loops accidentally
- Modify the array you’re iterating over
- Use
for...infor arrays (usefor...of) - Nest loops too deeply (hard to read)
- Use single-letter variables without context
// Bad - infinite loop
while (true) {
console.log('This never stops!');
}
// Bad - modifying while looping
for (const item of array) {
array.push(item); // Creates infinite loop!
}
// Bad - too complex
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
for (let k = 0; k < c.length; k++) {
// Hard to understand
}
}
}
Common Mistakes
1. Off-by-One Errors
// Wrong - skips last element
for (let i = 0; i < array.length - 1; i++) {
console.log(array[i]);
}
// Correct
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
2. Infinite Loops
// Wrong - never increments
let i = 0;
while (i < 5) {
console.log(i);
// Forgot i++; - infinite loop!
}
// Correct
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
3. Using for…in with Arrays
const numbers = [10, 20, 30];
// Wrong - gives indices as strings
for (const num in numbers) {
console.log(typeof num); // "string"
}
// Correct - use for...of
for (const num of numbers) {
console.log(num); // 10, 20, 30
}
Summary
| Loop Type | Use Case | Example |
|---|---|---|
for |
Known iterations | for (let i = 0; i < 10; i++) |
while |
Unknown iterations | while (condition) |
do...while |
At least one iteration | do { } while (condition) |
for...of |
Iterate array items | for (const item of array) |
for...in |
Iterate object keys | for (const key in object) |
Control Flow:
break- exit loop immediatelycontinue- skip to next iteration
Best Choice:
- Arrays →
for...of - Objects →
for...in - Known count →
for - Unknown count →
while
Next Article: Variables