JavaScript Loops & Iteration
Master JavaScript loops including for, while, do-while, and modern iteration methods for efficient data processing. This is a foundational concept in programming and web interactivity that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world JavaScript experience. Take your time with each section and practice the examples
Loop Fundamentals
Loops allow you to execute a block of code multiple times. JavaScript provides several types of loops for different iteration scenarios, from basic counting to complex data processing.. This is an essential concept that every JavaScript developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
For Loop Examples
// Basic for loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// For loop with array
const fruits = ['apple', 'banana', 'orange', 'grape'];
for (let i = 0; i < fruits.length; i++) {
console.log(`Fruit ${i + 1}: ${fruits[i]}`);
}
// For...in loop (for object properties)
const person = {
name: 'John',
age: 30,
city: 'NYC'
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// For...of loop (for iterable values)
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(`Color: ${color}`);
}
// For...of with strings
const message = 'Hello';
for (let char of message) {
console.log(`Character: ${char}`);
}
// Nested for loops
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
// For loop with break
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit loop when i equals 5
}
console.log(i);
}
// For loop with continue
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(`Odd number: ${i}`);
}While & Do-While Loops
// While loop
let count = 0;
while (count < 5) {
console.log(`Count: ${count}`);
count++;
}
// While loop with condition
let password = 'secret123';
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
const input = prompt('Enter password:');
if (input === password) {
console.log('Access granted!');
break;
} else {
attempts++;
console.log(`Attempt ${attempts} failed. ${maxAttempts - attempts} attempts remaining.`);
}
}
if (attempts >= maxAttempts) {
console.log('Access denied. Too many failed attempts.');
}
// Do-while loop (executes at least once)
let number = 1;
do {
console.log(`Number: ${number}`);
number *= 2;
} while (number < 10);
// While loop for data processing
let data = [1, 2, 3, 4, 5];
let index = 0;
let sum = 0;
while (index < data.length) {
sum += data[index];
index++;
}
console.log(`Sum: ${sum}`);
// While loop with array modification
let numbers = [1, 2, 3, 4, 5];
let i = 0;
while (i < numbers.length) {
if (numbers[i] % 2 === 0) {
numbers.splice(i, 1); // Remove even numbers
} else {
i++;
}
}
console.log('Odd numbers only:', numbers);Modern Iteration Methods
// Array forEach method
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => {
console.log(`Number ${index + 1}: ${number}`);
});
// forEach with objects
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 }
];
users.forEach((user, index) => {
console.log(`User ${index + 1}: ${user.name} (${user.age})`);
});
// Map method (creates new array)
const doubled = numbers.map(num => num * 2);
console.log('Doubled numbers:', doubled);
const userNames = users.map(user => user.name);
console.log('User names:', userNames);
// Filter method
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log('Even numbers:', evenNumbers);
const adults = users.filter(user => user.age >= 30);
console.log('Adults:', adults);
// Reduce method
const total = numbers.reduce((sum, num) => sum + num, 0);
console.log('Total:', total);
const oldestUser = users.reduce((oldest, user) =>
user.age > oldest.age ? user : oldest
);
console.log('Oldest user:', oldestUser);
// Find method
const firstEven = numbers.find(num => num % 2 === 0);
console.log('First even number:', firstEven);
const john = users.find(user => user.name === 'John');
console.log('John:', john);
// Some and Every methods
const hasEven = numbers.some(num => num % 2 === 0);
console.log('Has even numbers:', hasEven);
const allAdults = users.every(user => user.age >= 18);
console.log('All adults:', allAdults);
// For...of with different iterables
// Arrays
for (let num of numbers) {
console.log(num);
}
// Strings
for (let char of 'Hello') {
console.log(char);
}
// Sets
const uniqueNumbers = new Set([1, 2, 2, 3, 3, 4]);
for (let num of uniqueNumbers) {
console.log(num);
}
// Maps
const userMap = new Map([
['john', { name: 'John', age: 30 }],
['jane', { name: 'Jane', age: 25 }]
]);
for (let [key, value] of userMap) {
console.log(`${key}: ${value.name}`);
}Practice Exercise: Loops
// Exercise: Build a Number Guessing Game
function numberGuessingGame() {
const secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
const maxAttempts = 10;
console.log('Welcome to the Number Guessing Game!');
console.log('I'm thinking of a number between 1 and 100.');
while (attempts < maxAttempts) {
attempts++;
const guess = parseInt(prompt(`Attempt ${attempts}/${maxAttempts}: Enter your guess:`));
if (isNaN(guess)) {
console.log('Please enter a valid number.');
continue;
}
if (guess === secretNumber) {
console.log(`Congratulations! You guessed it in ${attempts} attempts!`);
return;
} else if (guess < secretNumber) {
console.log('Too low! Try again.');
} else {
console.log('Too high! Try again.');
}
}
console.log(`Game over! The number was ${secretNumber}.`);
}
// Exercise: Build a Data Processing System
function processData(data) {
const results = {
total: 0,
average: 0,
min: Infinity,
max: -Infinity,
evenCount: 0,
oddCount: 0,
positiveCount: 0,
negativeCount: 0
};
// Process each number
for (let num of data) {
results.total += num;
if (num < results.min) results.min = num;
if (num > results.max) results.max = num;
if (num % 2 === 0) {
results.evenCount++;
} else {
results.oddCount++;
}
if (num > 0) {
results.positiveCount++;
} else if (num < 0) {
results.negativeCount++;
}
}
results.average = results.total / data.length;
return results;
}
// Exercise: Build a Pattern Generator
function generatePattern(rows) {
for (let i = 1; i <= rows; i++) {
let pattern = '';
for (let j = 1; j <= i; j++) {
pattern += '* ';
}
console.log(pattern);
}
}
function generateNumberPattern(rows) {
for (let i = 1; i <= rows; i++) {
let pattern = '';
for (let j = 1; j <= i; j++) {
pattern += j + ' ';
}
console.log(pattern);
}
}
// Test the functions
const sampleData = [1, -2, 3, -4, 5, 6, -7, 8, 9, -10];
const stats = processData(sampleData);
console.log('Data Statistics:', stats);
console.log('Star Pattern:');
generatePattern(5);
console.log('Number Pattern:');
generateNumberPattern(5);