JavaScript BasicsFeatured

JavaScript Loops: Master All Loop Types with Examples

Learn all JavaScript loop types including for, while, do-while, for...in, for...of loops. Understand when to use each loop with practical examples.

By JavaScript Document Team
loopsiterationbasicscontrol-flowfundamentals

Loops are fundamental control structures in JavaScript that allow you to execute code repeatedly. This comprehensive guide covers all types of loops in JavaScript with practical examples and best practices.

The for Loop

The classic for loop is the most common loop structure, perfect when you know how many iterations you need.

Basic for Loop Syntax

// Basic syntax
for (initialization; condition; update) {
  // code to execute
}

// Example: Count from 0 to 4
for (let i = 0; i < 5; i++) {
  console.log(i); // 0, 1, 2, 3, 4
}

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

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

for Loop with Arrays

const fruits = ['apple', 'banana', 'orange', 'grape'];

// Traditional array iteration
for (let i = 0; i < fruits.length; i++) {
  console.log(`${i}: ${fruits[i]}`);
}

// Reverse iteration
for (let i = fruits.length - 1; i >= 0; i--) {
  console.log(fruits[i]);
}

// Every other element
for (let i = 0; i < fruits.length; i += 2) {
  console.log(fruits[i]); // apple, orange
}

Multiple Variables in for Loop

// Multiple initializations and updates
for (let i = 0, j = 10; i < j; i++, j--) {
  console.log(`i: ${i}, j: ${j}`);
}
// Output: i: 0, j: 10
//         i: 1, j: 9
//         i: 2, j: 8
//         i: 3, j: 7
//         i: 4, j: 6

// Matrix iteration
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

for (let i = 0; i < matrix.length; i++) {
  for (let j = 0; j < matrix[i].length; j++) {
    console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`);
  }
}

Infinite for Loop

// Infinite loop (be careful!)
// for (;;) {
//   console.log('This runs forever');
// }

// Practical infinite loop with break
for (;;) {
  const input = prompt('Enter "quit" to exit:');
  if (input === 'quit') {
    break;
  }
  console.log(`You entered: ${input}`);
}

The while Loop

The while loop executes as long as a condition is true. Use it when you don't know the exact number of iterations.

Basic while Loop

// Basic syntax
let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

// Reading until condition
let sum = 0;
let num = 1;
while (sum < 100) {
  sum += num;
  num++;
}
console.log(`Sum reached ${sum} at number ${num - 1}`);

// Processing queue
const tasks = ['task1', 'task2', 'task3'];
while (tasks.length > 0) {
  const currentTask = tasks.shift();
  console.log(`Processing: ${currentTask}`);
}

while Loop Patterns

// Countdown timer
let seconds = 10;
while (seconds > 0) {
  console.log(`${seconds} seconds remaining`);
  seconds--;
}
console.log("Time's up!");

// Finding first match
const numbers = [1, 3, 5, 8, 10, 13];
let index = 0;
while (index < numbers.length && numbers[index] % 2 !== 0) {
  index++;
}
console.log(`First even number at index: ${index}`);

// Validation loop
let userInput;
while (!userInput || userInput.length < 3) {
  userInput = prompt('Enter at least 3 characters:');
}
console.log(`Valid input: ${userInput}`);

The do...while Loop

The do...while loop always executes at least once, then checks the condition.

Basic do...while Loop

// Basic syntax
let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);

// Executes at least once even if condition is false
let x = 10;
do {
  console.log('This runs at least once');
  x++;
} while (x < 10); // Condition is false from start

// Menu system
let choice;
do {
  console.log('Menu:');
  console.log('1. Option 1');
  console.log('2. Option 2');
  console.log('3. Exit');
  choice = parseInt(prompt('Enter choice:'));

  switch (choice) {
    case 1:
      console.log('You chose Option 1');
      break;
    case 2:
      console.log('You chose Option 2');
      break;
  }
} while (choice !== 3);

do...while Use Cases

// Retry mechanism
let attempts = 0;
let success = false;
do {
  attempts++;
  // Simulate operation that might fail
  success = Math.random() > 0.7;
  console.log(`Attempt ${attempts}: ${success ? 'Success' : 'Failed'}`);
} while (!success && attempts < 5);

// Input validation
let password;
do {
  password = prompt('Enter password (min 8 chars):');
} while (!password || password.length < 8);

// Game loop
let playing = true;
let score = 0;
do {
  // Game logic
  score += Math.floor(Math.random() * 10);
  console.log(`Current score: ${score}`);

  if (score >= 50) {
    console.log('You win!');
    playing = false;
  } else {
    playing = confirm('Continue playing?');
  }
} while (playing);

The for...in Loop

The for...in loop iterates over enumerable properties of an object.

Object Iteration with for...in

const person = {
  name: 'John',
  age: 30,
  city: 'New York',
  occupation: 'Developer',
};

// Iterate over object properties
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// Check hasOwnProperty
for (const prop in person) {
  if (person.hasOwnProperty(prop)) {
    console.log(`Own property - ${prop}: ${person[prop]}`);
  }
}

// Nested objects
const company = {
  name: 'Tech Corp',
  employees: {
    john: { role: 'Developer', salary: 75000 },
    jane: { role: 'Designer', salary: 70000 },
  },
};

for (const dept in company) {
  if (typeof company[dept] === 'object') {
    console.log(`${dept}:`);
    for (const item in company[dept]) {
      console.log(`  ${item}:`, company[dept][item]);
    }
  } else {
    console.log(`${dept}: ${company[dept]}`);
  }
}

for...in with Arrays (Not Recommended)

const arr = ['a', 'b', 'c'];
arr.customProperty = 'custom';

// for...in includes non-numeric properties
for (const index in arr) {
  console.log(`${index}: ${arr[index]}`);
}
// Output: 0: a, 1: b, 2: c, customProperty: custom

// Better to use for...of or traditional for loop for arrays

The for...of Loop

The for...of loop iterates over iterable objects (arrays, strings, maps, sets, etc.).

Arrays with for...of

const colors = ['red', 'green', 'blue'];

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

// With destructuring
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
];

for (const { name, age } of users) {
  console.log(`${name} is ${age} years old`);
}

// With entries()
for (const [index, value] of colors.entries()) {
  console.log(`${index}: ${value}`);
}

Strings with for...of

const str = 'Hello';

// Iterate over characters
for (const char of str) {
  console.log(char); // H, e, l, l, o
}

// Works with Unicode
const emoji = '😀🎉';
for (const char of emoji) {
  console.log(char); // 😀, 🎉
}

// Character codes
for (const char of 'ABC') {
  console.log(`${char}: ${char.charCodeAt(0)}`);
}

Maps and Sets with for...of

// Set iteration
const uniqueNumbers = new Set([1, 2, 3, 2, 1]);
for (const num of uniqueNumbers) {
  console.log(num); // 1, 2, 3
}

// Map iteration
const userRoles = new Map([
  ['alice', 'admin'],
  ['bob', 'user'],
  ['charlie', 'moderator'],
]);

for (const [user, role] of userRoles) {
  console.log(`${user}: ${role}`);
}

// Just keys or values
for (const user of userRoles.keys()) {
  console.log(`User: ${user}`);
}

for (const role of userRoles.values()) {
  console.log(`Role: ${role}`);
}

Loop Control Statements

break Statement

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

// Break in nested loops
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outer; // Break outer loop
    }
    console.log(`i: ${i}, j: ${j}`);
  }
}

// Search and break
const items = ['apple', 'banana', 'orange', 'grape'];
let found = null;
for (const item of items) {
  if (item === 'orange') {
    found = item;
    break;
  }
}
console.log(`Found: ${found}`);

continue Statement

// Skip current iteration
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) {
    continue; // Skip even numbers
  }
  console.log(i); // 1, 3, 5, 7, 9
}

// Continue in nested loops
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) {
      continue; // Skip when j is 1
    }
    console.log(`i: ${i}, j: ${j}`);
  }
}

// Filter with continue
const numbers = [1, -2, 3, -4, 5];
console.log('Positive numbers:');
for (const num of numbers) {
  if (num < 0) continue;
  console.log(num);
}

Labels

// Label with break
outerLoop: for (let i = 0; i < 3; i++) {
  innerLoop: for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outerLoop;
    }
    console.log(`${i},${j}`);
  }
}

// Label with continue
outerLoop: for (let i = 0; i < 3; i++) {
  innerLoop: for (let j = 0; j < 3; j++) {
    if (i === 1) {
      continue outerLoop;
    }
    console.log(`${i},${j}`);
  }
}

Performance Considerations

Loop Optimization

const arr = new Array(1000000).fill(1);

// Cache length (minor optimization)
console.time('Cached length');
const len = arr.length;
for (let i = 0; i < len; i++) {
  // Process
}
console.timeEnd('Cached length');

// Reverse loop (sometimes faster)
console.time('Reverse');
for (let i = arr.length - 1; i >= 0; i--) {
  // Process
}
console.timeEnd('Reverse');

// While loop
console.time('While');
let i = arr.length;
while (i--) {
  // Process
}
console.timeEnd('While');

Choosing the Right Loop

// Use for loop when:
// - You know the number of iterations
// - You need index access
for (let i = 0; i < 10; i++) {
  console.log(i);
}

// Use while when:
// - Condition-based iteration
// - Unknown number of iterations
while (condition) {
  // Process
}

// Use do...while when:
// - Need at least one execution
// - Menu-driven programs
do {
  // Execute at least once
} while (condition);

// Use for...of when:
// - Iterating over array values
// - Working with iterables
for (const value of array) {
  console.log(value);
}

// Use for...in when:
// - Iterating over object properties
// - Need property names
for (const key in object) {
  console.log(key, object[key]);
}

Common Loop Patterns

Array Processing

// Transform array
const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (const num of numbers) {
  doubled.push(num * 2);
}

// Filter array
const evens = [];
for (const num of numbers) {
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// Accumulate/Reduce
let sum = 0;
for (const num of numbers) {
  sum += num;
}

Object Processing

// Clone object
const original = { a: 1, b: 2, c: 3 };
const clone = {};
for (const key in original) {
  if (original.hasOwnProperty(key)) {
    clone[key] = original[key];
  }
}

// Filter object properties
const filtered = {};
for (const key in original) {
  if (original[key] > 1) {
    filtered[key] = original[key];
  }
}

// Count properties
let count = 0;
for (const key in original) {
  if (original.hasOwnProperty(key)) {
    count++;
  }
}

Nested Data Structures

// 2D array processing
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

// Sum all elements
let total = 0;
for (const row of matrix) {
  for (const value of row) {
    total += value;
  }
}

// Find in nested structure
const data = {
  users: [
    { id: 1, name: 'John', tags: ['admin', 'user'] },
    { id: 2, name: 'Jane', tags: ['user'] },
  ],
};

let foundUser = null;
outer: for (const user of data.users) {
  for (const tag of user.tags) {
    if (tag === 'admin') {
      foundUser = user;
      break outer;
    }
  }
}

Best Practices

  1. Choose the appropriate loop for your use case
  2. Avoid infinite loops - ensure loop condition will eventually be false
  3. Use for...of for arrays instead of for...in
  4. Cache array length in performance-critical code
  5. Use break and continue to control flow efficiently
  6. Consider functional methods (map, filter, reduce) for array transformations
  7. Be careful with async operations in loops

Conclusion

JavaScript provides various loop constructs, each suited for different scenarios. Understanding when and how to use each type of loop is essential for writing efficient and readable code. While modern JavaScript offers functional alternatives like map(), filter(), and reduce(), traditional loops remain important for many programming tasks, especially when you need fine-grained control over the iteration process.