Loops

JavaScript Loop Types

JavaScript provides several ways to loop through data: for, while, do-while, for...in, for...of, and array methods like forEach, map, filter, etc.

Try Different Loops

Code Editor
Console Output
Click "Run" to execute your code...

Example 1: for Loop

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

// Loop through array
const fruits = ['apple', 'banana', 'orange', 'grape'];
for (let i = 0; i < fruits.length; i++) {
  console.log(`${i}: ${fruits[i]}`);
}
// 0: apple
// 1: banana
// 2: orange
// 3: grape

// Reverse loop
for (let i = fruits.length - 1; i >= 0; i--) {
  console.log(fruits[i]);
}
// grape, orange, banana, apple

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

// Nested loops
for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(`i=${i}, j=${j}`);
  }
}

// Break and continue
for (let i = 0; i < 10; i++) {
  if (i === 3) continue; // Skip 3
  if (i === 7) break;     // Stop at 7
  console.log(i); // 0, 1, 2, 4, 5, 6
}

Example 2: while and do-while Loops

// while loop - checks condition first
let count = 0;
while (count < 5) {
  console.log(`Count: ${count}`);
  count++;
}
// Count: 0, 1, 2, 3, 4

// do-while loop - executes at least once
let num = 0;
do {
  console.log(`Num: ${num}`);
  num++;
} while (num < 3);
// Num: 0, 1, 2

// do-while executes even if condition is false initially
let x = 10;
do {
  console.log('This runs once'); // Executes once
  x++;
} while (x < 5);

// Practical: Input validation
function getValidInput(input) {
  let attempts = 0;
  while (attempts < 3) {
    if (input > 0) {
      return input;
    }
    console.log('Invalid input, try again');
    attempts++;
    input = Math.random() * 10; // Simulating new input
  }
  return null;
}

// Finding first match
const numbers = [1, 3, 5, 8, 9, 11];
let i = 0;
while (i < numbers.length) {
  if (numbers[i] % 2 === 0) {
    console.log(`First even number: ${numbers[i]}`);
    break;
  }
  i++;
}

Example 3: for...in Loop (Objects)

// for...in iterates over enumerable properties
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}
// name: John
// age: 30
// city: New York

// with arrays (not recommended - gives indices)
const arr = ['a', 'b', 'c'];
for (let index in arr) {
  console.log(`${index}: ${arr[index]}`);
}
// 0: a, 1: b, 2: c

// Checking own properties
const obj = Object.create({ inherited: 'value' });
obj.own = 'own value';

for (let key in obj) {
  console.log(`${key}: ${obj[key]}`);
}
// own: own value
// inherited: value (includes inherited!)

// Filter to only own properties
for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(`${key}: ${obj[key]}`);
  }
}
// own: own value

// Better alternatives for objects
const user = { name: 'Alice', age: 25, role: 'Admin' };

// Object.keys()
Object.keys(user).forEach(key => {
  console.log(`${key}: ${user[key]}`);
});

// Object.entries()
Object.entries(user).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

// Object.values()
Object.values(user).forEach(value => {
  console.log(value);
});

Example 4: for...of Loop (Iterables)

// for...of iterates over iterable objects (arrays, strings, Maps, Sets)
const colors = ['red', 'green', 'blue'];

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

// With strings
const text = 'Hello';
for (let char of text) {
  console.log(char);
}
// H, e, l, l, o

// With index using entries()
for (let [index, value] of colors.entries()) {
  console.log(`${index}: ${value}`);
}
// 0: red, 1: green, 2: blue

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

// With Map
const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3']
]);

for (let [key, value] of map) {
  console.log(`${key}: ${value}`);
}

// Only keys
for (let key of map.keys()) {
  console.log(key);
}

// Only values
for (let value of map.values()) {
  console.log(value);
}

// for...of vs for...in
const array = ['a', 'b', 'c'];

// for...in gives indices (not recommended for arrays)
for (let i in array) {
  console.log(i); // '0', '1', '2' (strings!)
}

// for...of gives values (recommended for arrays)
for (let val of array) {
  console.log(val); // 'a', 'b', 'c'
}

Example 5: Array Methods (Functional Loops)

const numbers = [1, 2, 3, 4, 5];

// forEach - executes for each element
numbers.forEach((num, index, arr) => {
  console.log(`Index ${index}: ${num}`);
});

// map - transforms each element, returns new array
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// filter - selects elements, returns new array
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]

// reduce - reduces to single value
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

// some - checks if at least one element matches
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true

// every - checks if all elements match
const allPositive = numbers.every(num => num > 0);
console.log(allPositive); // true

// find - finds first matching element
const found = numbers.find(num => num > 3);
console.log(found); // 4

// findIndex - finds index of first match
const index = numbers.findIndex(num => num > 3);
console.log(index); // 3

// Chaining methods
const result = numbers
  .filter(num => num > 2)     // [3, 4, 5]
  .map(num => num * 2)        // [6, 8, 10]
  .reduce((acc, num) => acc + num, 0); // 24

console.log(result); // 24

// Performance comparison
const largeArray = Array.from({ length: 1000000 }, (_, i) => i);

console.time('for loop');
let sum1 = 0;
for (let i = 0; i < largeArray.length; i++) {
  sum1 += largeArray[i];
}
console.timeEnd('for loop');

console.time('forEach');
let sum2 = 0;
largeArray.forEach(num => sum2 += num);
console.timeEnd('forEach');

console.time('reduce');
const sum3 = largeArray.reduce((acc, num) => acc + num, 0);
console.timeEnd('reduce');

// for loop is typically fastest, but forEach/map/filter are more readable

Key Points

  • for loop: Traditional, best for performance, full control
  • while/do-while: Use when iterations count is unknown
  • for...in: Iterates object properties (avoid for arrays)
  • for...of: Iterates iterable values (arrays, strings, Sets, Maps)
  • forEach/map/filter: Functional approach, cleaner code
  • Use break to exit loop, continue to skip iteration
  • Choose based on readability vs performance needs