Back to JavaScript
2026-01-307 min read

looping statements (JavaScript)

Learn looping statements (JavaScript) step by step with clear examples and exercises.

Title: Mastering Looping Statements in JavaScript

Why This Matters

Looping statements are crucial for automating repetitive tasks, making your JavaScript code more efficient and dynamic. Understanding how to use them effectively can help you tackle complex problems, write cleaner code, and prepare for real-world programming scenarios, including coding interviews and debugging common bugs in your applications.

Prerequisites

To get the most out of this lesson, you should have a basic understanding of JavaScript syntax, variables, functions, and control structures like if-else statements. If you're new to JavaScript or need a refresher, consider checking out our JavaScript Fundamentals lesson first.

What are Looping Statements?

Looping statements allow you to repeatedly execute a block of code as long as a certain condition is met. JavaScript provides three main types of looping statements: for, while, and do-while. Each one has its unique use cases, but they all serve the same purpose—to simplify repetitive tasks.

The for Loop

The for loop is a common choice when you know exactly how many times you want to iterate through a specific range of values or an array. Here's the syntax:

for (initialization; condition; increment/decrement) {
// code to be executed
}
  • Initialization: This is where you declare and initialize your counter variable. For example, let i = 0;.
  • Condition: The loop checks if the condition is true or false. If it's true, the loop continues; otherwise, it stops. In our example, we might use i < 10.
  • Increment/Decrement: This part updates the counter variable after each iteration. For instance, i++ increments the value of i, while i-- decrements it.

Here's an example that prints numbers from 0 to 9 using a for loop:

for (let i = 0; i < 10; i++) {
console.log(i);
}

The while Loop

The while loop continues executing as long as the specified condition is true. Here's its syntax:

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

Unlike the for loop, you don't explicitly declare a counter variable in the while loop. Instead, you manage it inside the loop body. Here's an example that prints numbers from 0 to 9 using a while loop:

let i = 0;
while (i < 10) {
console.log(i);
i++;
}

The do-while Loop

The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition. Here's its syntax:

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

This can be useful when you want to ensure that the loop body is executed at least once, even if the condition is eventually false. For example, consider a scenario where you want to prompt the user for input until they provide valid data:

let userInput;
do {
userInput = prompt("Please enter a number between 0 and 9");
} while (userInput < 0 || userInput > 9);
console.log(userInput);

Breaking Out of Loops

You can use the break statement to exit a loop prematurely when a specific condition is met. For example, if you're searching for a particular value in an array and find it, there's no need to continue searching:

let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 4) {
console.log("Found the number 4!");
break;
}
}

Looping Through Arrays with forEach()

JavaScript also provides a built-in method called forEach() for iterating through arrays without using traditional loops. Here's an example:

let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});

Core Concept

Understanding the Counter Variable

In a for, while, or do-while loop, you'll often need to keep track of your progress through the iterations using a counter variable. This variable is usually initialized at the start of the loop and updated after each iteration. The loop continues as long as the counter variable meets the specified condition.

Using Loops with Arrays

Looping statements are especially useful when working with arrays, as they allow you to iterate through each element in a collection efficiently. You can use for, while, or do-while loops for this purpose, but forEach() is often the preferred choice due to its simplicity and readability.

Nested Loops

Nested loops, or loops within loops, can be useful when you need to iterate through multiple arrays simultaneously or perform complex iteration patterns. Be aware that nested loops can lead to more complex code and potential performance issues if not managed carefully.

Worked Example

Let's create a simple program that calculates the sum of all even numbers in an array using a for loop, the break statement, and nested loops:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = 0;

// Outer loop to iterate through each number in the array
for (let i = 0; i < numbers.length; i++) {
// Check if the current number is even
if (numbers[i] % 2 === 0) {
// Inner loop to check for multiples of 3 within the even numbers
for (let j = i + 1; j < numbers.length; j++) {
if (numbers[j] % 3 === 0 && numbers[j] > numbers[i]) {
sum += numbers[j];
break; // Exit the inner loop once we find a suitable multiple of 3
}
}
}
}
console.log(sum); // Output: 24 or less

Common Mistakes

Forgetting to Initialize the Counter Variable

If you forget to initialize your counter variable, you'll get an undefined error when trying to use it in the condition.

for (let i; i < 10; i++) { // Missing initialization
console.log(i);
}

Incorrect Condition or Increment/Decrement in a for Loop

Incorrect conditions or improper increment/decrement can cause your loop to run too many or too few times, leading to unexpected results:

for (let i = 0; i < 10; i++) { // Should be i <= 9
console.log(i);
}

Using a while Loop When a for Loop Would Be Better

Using the wrong loop type can make your code harder to read and maintain:

let numbers = [1, 2, 3, 4, 5];
let sum = 0;
let i = 0;
while (i < numbers.length) { // for loop is more appropriate here
sum += numbers[i];
i++;
}

Not Using the break Statement When Needed

Not using break when you should can lead to unnecessary iterations and slower performance:

let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) { // Do something with number 3 and continue the loop
console.log("Found number 3!");
} else if (numbers[i] === 5) { // Exit the loop when we find number 5
break;
}
}

Practice Questions

  1. Write a for loop that prints the multiplication table for 7 (from 7 x 1 to 7 x 12).
for (let i = 1; i <= 12; i++) {
console.log(`7 * ${i} = ${7 * i}`);
}
  1. Using a while loop, create a program that asks the user for their name and greets them accordingly.
let userName;
do {
userName = prompt("What is your name?");
} while (!userName);
console.log(`Hello, ${userName}! Nice to meet you.`);
  1. Write a do-while loop that prompts the user to enter a number between 1 and 10 until they provide a valid input.
let userInput;
do {
userInput = prompt("Please enter a number between 1 and 10");
} while (userInput < 1 || userInput > 10);
console.log(`You entered: ${userInput}`);
  1. Create an array of strings containing the names of your favorite programming languages. Use the forEach() method to print each language name.
let languages = ["JavaScript", "Python", "Ruby", "Go", "Swift"];
languages.forEach(function(language) {
console.log(language);
});
  1. Using a for loop, write a program that calculates the sum of all even numbers in the range from 1 to 100.
let sum = 0;
for (let i = 2; i <= 100; i += 2) {
sum += i;
}
console.log(sum); // Output: 2550
  1. Write a program that finds the largest prime number in the range from 2 to 100 using nested loops and the break statement.
let largestPrime = -1;
for (let i = 2; i <= 100; i++) {
// Check if the current number is prime by testing divisibility from 2 to the square root of the number
for (let j = 2; j * j <= i; j++) {
if (i % j === 0) break; // If the number is not prime, exit the inner loop and continue with the next number
}
// If we've made it through the inner loop without finding a divisor, the current number is prime
if (largestPrime < i) largestPrime = i;
}
console.log(largestPrime); // Output: 97

FAQ

What happens if I forget the semicolon at the end of a line in JavaScript?

Forgetting a semicolon can lead to unexpected behavior, as the interpreter may interpret the next line as part of the same statement. This can cause syntax errors or runtime issues. To avoid such problems, always include semicolons at the end of your lines.

Can I use multiple statements in a single line with JavaScript?

Yes, you can use multiple statements on a single line by separating them with a semicolon. However, it's generally considered bad practice and can make your code harder to read and maintain. Stick to one statement per line for better readability.

looping statements (JavaScript) | JavaScript | XQA Learn