Master JavaScript loops and iteration patterns for repetitive tasks and data processing
Loops are fundamental programming constructs that allow you to execute code repeatedly. Instead of writing the same code multiple times, loops let you automate repetitive tasks efficiently.
Whether you're processing arrays, creating patterns, or validating user input, loops are essential tools in every JavaScript developer's toolkit. In this lesson, you'll master different types of loops and learn when to use each one for maximum effectiveness.
The for loop is perfect when you know exactly how many times you want to repeat something.
Basic For Loop Syntax:
1for (initialization; condition; increment) {
2 // Code to execute repeatedly
3}
4
5// Example: Count from 1 to 5
6for (let i = 1; i <= 5; i++) {
7 console.log("Count: " + i);
8}
9// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5Understanding For Loop Components:
Practical Examples:
1// Generate multiplication table
2for (let i = 1; i <= 10; i++) {
3 console.log(`5 × ${i} = ${5 * i}`);
4}
5
6// Create array of squares
7const squares = [];
8for (let i = 1; i <= 5; i++) {
9 squares.push(i * i);
10}
11console.log(squares); // [1, 4, 9, 16, 25]
12
13// Process array with index access
14const fruits = ['apple', 'banana', 'orange'];
15for (let i = 0; i < fruits.length; i++) {
16 console.log(`${i + 1}. ${fruits[i]}`);
17}Common For Loop Patterns:
While loops are perfect when you don't know exactly how many iterations you need, but you know the condition that should stop the loop.
While Loop:
1while (condition) {
2 // Code to execute
3 // Make sure to update the condition!
4}
5
6// Example: Keep asking until valid input
7let userInput = '';
8while (userInput !== 'yes') {
9 userInput = prompt('Do you want to continue? (yes/no)');
10 if (userInput === 'no') break;
11}Do-While Loop:
1do {
2 // Code executes at least once
3} while (condition);
4
5// Example: Menu system
6let choice;
7do {
8 choice = prompt('Choose: 1) Start 2) Settings 3) Exit');
9 switch(choice) {
10 case '1': console.log('Starting game...'); break;
11 case '2': console.log('Opening settings...'); break;
12 case '3': console.log('Goodbye!'); break;
13 default: console.log('Invalid choice!');
14 }
15} while (choice !== '3');When to Use Each:
Common While Loop Patterns:
1// Random number generation
2let randomNum;
3while (randomNum !== 7) {
4 randomNum = Math.floor(Math.random() * 10) + 1;
5 console.log(`Generated: ${randomNum}`);
6}
7
8// Processing until condition met
9let password = '';
10while (password.length < 8) {
11 password = prompt('Enter password (min 8 characters):');
12}Sometimes you need to alter the normal flow of a loop. Break and continue statements give you this control.
Break Statement:
Exits the loop completely when encountered.
1// Find first even number
2for (let i = 1; i <= 10; i++) {
3 if (i % 2 === 0) {
4 console.log(`First even number: ${i}`);
5 break; // Exit the loop
6 }
7}
8
9// Search array for specific value
10const numbers = [1, 3, 7, 2, 9, 4];
11for (let i = 0; i < numbers.length; i++) {
12 if (numbers[i] > 5) {
13 console.log(`Found number greater than 5: ${numbers[i]}`);
14 break;
15 }
16}Continue Statement:
Skips the rest of the current iteration and moves to the next one.
1// Print only odd numbers
2for (let i = 1; i <= 10; i++) {
3 if (i % 2 === 0) {
4 continue; // Skip even numbers
5 }
6 console.log(`Odd number: ${i}`);
7}
8
9// Process valid entries only
10const data = ['apple', '', 'banana', null, 'orange', undefined];
11for (let i = 0; i < data.length; i++) {
12 if (!data[i]) {
13 continue; // Skip empty/null/undefined values
14 }
15 console.log(`Processing: ${data[i]}`);
16}Best Practices:
Nested loops allow you to work with multi-dimensional data or create complex patterns.
Basic Nested Loop Structure:
1for (let outer = 0; outer < outerLimit; outer++) {
2 for (let inner = 0; inner < innerLimit; inner++) {
3 // Inner loop code
4 console.log(`Outer: ${outer}, Inner: ${inner}`);
5 }
6}Practical Examples:
1. Multiplication Table:
1console.log('Multiplication Table:');
2for (let i = 1; i <= 5; i++) {
3 let row = '';
4 for (let j = 1; j <= 5; j++) {
5 row += (i * j).toString().padStart(3, ' ') + ' ';
6 }
7 console.log(row);
8}2. Pattern Generation:
1// Create star pattern
2for (let i = 1; i <= 5; i++) {
3 let pattern = '';
4 for (let j = 1; j <= i; j++) {
5 pattern += '* ';
6 }
7 console.log(pattern);
8}
9// Output:
10// *
11// * *
12// * * *
13// * * * *
14// * * * * *3. 2D Array Processing:
1const matrix = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5];
6
7// Sum all elements
8let total = 0;
9for (let row = 0; row < matrix.length; row++) {
10 for (let col = 0; col < matrix[row].length; col++) {
11 total += matrix[row][col];
12 }
13}
14console.log(`Total: ${total}`); // 45Performance Considerations:
Modern JavaScript provides elegant ways to iterate over collections without manual index management.
For...of Loop (ES6):
Iterates over values in arrays, strings, and other iterable objects.
1// Array iteration
2const fruits = ['apple', 'banana', 'orange'];
3for (const fruit of fruits) {
4 console.log(fruit);
5}
6
7// String iteration
8const word = 'hello';
9for (const letter of word) {
10 console.log(letter);
11}
12
13// With index using entries()
14for (const [index, fruit] of fruits.entries()) {
15 console.log(`${index}: ${fruit}`);
16}For...in Loop:
Iterates over object properties and array indices.
1// Object iteration
2const person = {
3 name: 'John',
4 age: 30,
5 city: 'New York'
6};
7
8for (const key in person) {
9 console.log(`${key}: ${person[key]}`);
10}
11
12// Array iteration (gets indices)
13const colors = ['red', 'green', 'blue'];
14for (const index in colors) {
15 console.log(`${index}: ${colors[index]}`);
16}When to Use Each:
Use for...of when:
Use for...in when:
Comparison Example:
1const array = ['a', 'b', 'c'];
2
3// for...of gives values
4for (const value of array) {
5 console.log(value); // 'a', 'b', 'c'
6}
7
8// for...in gives indices
9for (const index in array) {
10 console.log(index); // '0', '1', '2'
11}Great work mastering JavaScript loops! You've learned to automate repetitive tasks and process data efficiently. Next, we'll explore Arrays & Array Methods, where you'll discover powerful built-in methods that work hand-in-hand with loops to manipulate and transform data collections. Get ready to level up your data processing skills!
Your progress is saved in this browser, on this device only.