Skip to main content

JavaScript Loops

Introduction

Loops are fundamental programming constructs that allow you to execute a block of code repeatedly. In JavaScript, loops are essential for tasks like iterating through arrays, processing collections of data, implementing game logic, and many other scenarios where repeated execution is required.

Instead of writing the same code multiple times, loops provide an efficient way to perform repetitive tasks with minimal code. JavaScript offers several types of loops, each with its own specific use cases and syntax.

Why Are Loops Important?

Imagine you need to print numbers from 1 to 100, or process each item in an array with hundreds of elements. Without loops, you would have to write the same code 100 times or more! Loops solve this problem by allowing you to write the code once and have it execute repeatedly under specified conditions.

Types of JavaScript Loops

JavaScript provides several types of loops:

  1. for loop
  2. while loop
  3. do-while loop
  4. for...of loop (for iterating over iterable objects)
  5. for...in loop (for iterating over object properties)

Let's explore each of these in detail.

The for Loop

The for loop is the most commonly used loop in JavaScript. It consists of three parts: initialization, condition, and iteration.

Syntax

javascript
for (initialization; condition; iteration) {
// code to be executed
}
  • Initialization: Executed once before the loop starts
  • Condition: Evaluated before each loop iteration; if true, the loop continues
  • Iteration: Executed after each loop iteration

Example: Counting from 1 to 5

javascript
for (let i = 1; i <= 5; i++) {
console.log(i);
}

Output:

1
2
3
4
5

How It Works:

  1. let i = 1 initializes the counter variable
  2. i <= 5 checks if the loop should continue
  3. i++ increments the counter after each iteration
  4. The loop body console.log(i) executes on each iteration

Practical Example: Summing Array Elements

javascript
const numbers = [10, 20, 30, 40, 50];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}

console.log("The sum is:", sum);

Output:

The sum is: 150

The while Loop

The while loop executes a block of code as long as a specified condition is true.

Syntax

javascript
while (condition) {
// code to be executed
}

Example: Counting Down from 5

javascript
let count = 5;
while (count > 0) {
console.log(count);
count--;
}
console.log("Blast off!");

Output:

5
4
3
2
1
Blast off!

When to Use while Loops

while loops are particularly useful when you don't know in advance how many times you need to iterate. For example, when you're waiting for a specific user input or processing data until a certain condition is met.

Practical Example: Random Number Generator

javascript
let target = Math.floor(Math.random() * 10) + 1;
let guess = 0;
let attempts = 0;

while (guess !== target) {
guess = Math.floor(Math.random() * 10) + 1;
attempts++;
console.log(`Attempt ${attempts}: guessed ${guess}`);
}

console.log(`Found the target ${target} in ${attempts} attempts!`);

Sample Output:

Attempt 1: guessed 7
Attempt 2: guessed 3
Attempt 3: guessed 9
Attempt 4: guessed 9
Attempt 5: guessed 2
Found the target 2 in 5 attempts!

The do-while Loop

The do-while loop is similar to the while loop, with one important difference: it executes the code block at least once before checking the condition.

Syntax

javascript
do {
// code to be executed
} while (condition);

Example: Menu System

javascript
let choice;

do {
choice = prompt("Select an option (1-3) or 'q' to quit:");

switch(choice) {
case '1':
console.log("You selected option 1");
break;
case '2':
console.log("You selected option 2");
break;
case '3':
console.log("You selected option 3");
break;
case 'q':
console.log("Exiting...");
break;
default:
console.log("Invalid option, try again");
}
} while (choice !== 'q');

When to Use do-while Loops

Use a do-while loop when you want to ensure that the code block executes at least once, regardless of the condition. This is useful for menu systems, user input validation, and similar scenarios.

The for...of Loop

The for...of loop is a modern JavaScript feature introduced in ES6 for iterating over iterable objects like arrays, strings, maps, sets, etc.

Syntax

javascript
for (const element of iterable) {
// code to be executed
}

Example: Iterating Over an Array

javascript
const fruits = ["Apple", "Banana", "Cherry", "Dragon fruit"];

for (const fruit of fruits) {
console.log(fruit);
}

Output:

Apple
Banana
Cherry
Dragon fruit

Advantages of for...of

  • Cleaner syntax compared to traditional for loops
  • Automatically handles the iteration details
  • Works with any iterable object
  • No need to track indexes or array lengths

Practical Example: Processing Characters in a String

javascript
const message = "Hello!";
let uppercaseChars = 0;

for (const char of message) {
if (char === char.toUpperCase() && char !== char.toLowerCase()) {
uppercaseChars++;
}
}

console.log(`The message has ${uppercaseChars} uppercase letter(s).`);

Output:

The message has 1 uppercase letter(s).

The for...in Loop

The for...in loop iterates over all enumerable properties of an object, including inherited properties.

Syntax

javascript
for (const key in object) {
// code to be executed
}

Example: Iterating Over Object Properties

javascript
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
occupation: "Developer"
};

for (const property in person) {
console.log(`${property}: ${person[property]}`);
}

Output:

firstName: John
lastName: Doe
age: 30
occupation: Developer

Important Note

for...in is primarily designed for objects. While it can be used with arrays, it's not recommended because:

  • It iterates over all enumerable properties, not just numeric indices
  • The order of iteration is not guaranteed
  • It's generally slower than other loops for arrays

For arrays, use for...of or the traditional for loop instead.

Loop Control Statements

JavaScript provides statements to control the flow of loops:

1. break

The break statement terminates the current loop and transfers control to the statement following the loop.

javascript
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Exit the loop when i equals 5
}
console.log(i);
}

Output:

1
2
3
4

2. continue

The continue statement skips the current iteration and proceeds to the next one.

javascript
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i equals 3
}
console.log(i);
}

Output:

1
2
4
5

Nested Loops

Loops can be nested within other loops, allowing you to work with multi-dimensional data structures or perform complex iterations.

Example: Multiplication Table

javascript
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} × ${j} = ${i * j}`);
}
console.log('---'); // Separator between tables
}

Output:

1 × 1 = 1
1 × 2 = 2
1 × 3 = 3
---
2 × 1 = 2
2 × 2 = 4
2 × 3 = 6
---
3 × 1 = 3
3 × 2 = 6
3 × 3 = 9
---

Real-World Applications

1. Data Processing

javascript
// Calculating average score of students
const studentScores = [
{ name: "Alice", score: 85 },
{ name: "Bob", score: 92 },
{ name: "Carol", score: 78 },
{ name: "Dave", score: 90 }
];

let totalScore = 0;
for (const student of studentScores) {
totalScore += student.score;
}

const averageScore = totalScore / studentScores.length;
console.log(`Average score: ${averageScore.toFixed(2)}`);

Output:

Average score: 86.25

2. DOM Manipulation

javascript
// Changing the color of all paragraphs on a page
const paragraphs = document.querySelectorAll('p');

for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.color = 'blue';
}

3. API Data Processing

javascript
// Processing a list of user data from an API
const users = [
{ id: 1, name: "John", isActive: true },
{ id: 2, name: "Jane", isActive: false },
{ id: 3, name: "Bob", isActive: true }
];

const activeUserNames = [];
for (const user of users) {
if (user.isActive) {
activeUserNames.push(user.name);
}
}

console.log("Active users:", activeUserNames.join(", "));

Output:

Active users: John, Bob

Common Loop Patterns

1. Array Transformation (Map operation)

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

for (const number of numbers) {
squared.push(number * number);
}

console.log(squared);

Output:

[1, 4, 9, 16, 25]

2. Filtering (Filter operation)

javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = [];

for (const number of numbers) {
if (number % 2 === 0) {
evenNumbers.push(number);
}
}

console.log(evenNumbers);

Output:

[2, 4, 6, 8, 10]

3. Accumulation (Reduce operation)

javascript
const cart = [
{ item: "Laptop", price: 999 },
{ item: "Keyboard", price: 79 },
{ item: "Mouse", price: 29 }
];

let total = 0;
for (const product of cart) {
total += product.price;
}

console.log(`Total: $${total}`);

Output:

Total: $1107

Performance Considerations

  1. Loop Selection: Choose the right loop for the job. For arrays, for or for...of loops are generally more efficient than for...in.

  2. Cache Array Length: When using traditional for loops with arrays, cache the array length outside the loop:

javascript
const arr = [1, 2, 3, 4, 5];
const len = arr.length; // Cache the length

for (let i = 0; i < len; i++) {
console.log(arr[i]);
}
  1. Minimize Work Inside Loops: Avoid expensive operations inside loops when possible.

  2. Early Exit: Use break to exit loops early when appropriate.

Infinite Loops and How to Avoid Them

Infinite loops occur when the loop condition never evaluates to false. These can crash browsers or applications.

Example of an Infinite Loop:

javascript
// DO NOT RUN THIS CODE
for (let i = 1; i > 0; i++) {
console.log(i);
}

Tips to Avoid Infinite Loops:

  1. Ensure your loop condition will eventually become false
  2. Make sure your iterator variable is properly updated
  3. Double-check your condition logic
  4. Set a maximum number of iterations as a safety measure

Summary

Loops are a critical component of JavaScript programming that allow for efficient code execution through repetition. In this guide, we've covered:

  • The basic loop types: for, while, and do-while
  • Modern loop constructs: for...of and for...in
  • Loop control statements: break and continue
  • Nested loops and their applications
  • Real-world applications and common patterns
  • Performance considerations
  • How to avoid infinite loops

By mastering loops, you gain the ability to work with collections of data, automate repetitive tasks, and implement complex algorithms efficiently.

Practice Exercises

  1. FizzBuzz: Write a program that prints numbers from 1 to 100, but for multiples of 3 print "Fizz" instead, for multiples of 5 print "Buzz", and for numbers that are multiples of both 3 and 5 print "FizzBuzz".

  2. Sum of Even Numbers: Write a function that calculates the sum of all even numbers between 1 and n, where n is a parameter.

  3. Array Filtering: Create a function that takes an array of numbers and returns a new array containing only the prime numbers.

  4. Nested Data Access: Given an array of student objects, each containing a name and an array of scores, calculate each student's average score.

Additional Resources

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)