Home/Blog/Programming/JavaScript loops tutorial: for loop, while loop, and more
JavaScript Loops Tutorial
Home/Blog/Programming/JavaScript loops tutorial: for loop, while loop, and more

JavaScript loops tutorial: for loop, while loop, and more

10 min read
May 19, 2025
content
Introduction to JavaScript Loop
How does a loop work?
Structure of a loop
Types of loop in JavaScript
1. The for loop
2. The while loop
3. The do...while loop
Comparison: while vs. do...while
4. The for...in loop
5. The for...of loop
Comparison: for...in vs. for...of
6. The forEach() method
Which loop to use?
Nested loops
Key considerations while using nested loops
Controlling loops: break and continue
The break statement
The continue statement
How to use loops in practice
Rendering a list of items in HTML
Filtering even numbers from an array
What to learn next
Continue learning advanced JavaScript concepts

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Ever tried manually processing 1,000 user records in JavaScript?

Not fun, and definitely not efficient.

That’s where loops shine.

They automate repetitive tasks, streamline code, and keep performance on point. Whether you’re processing user data, rendering UI elements, or solving complex algorithms, understanding loops is non-negotiable for developers.

In this tutorial, we’ll explore different types of loops in JavaScript, their syntax, and when to use them effectively. By the end of this blog, you will have a solid understanding of JavaScript loops, their use cases, and important considerations.

Learn JavaScript

Cover
Learn to Code: Javascript for Absolute Beginners

JavaScript is a versatile language essential for web development, working alongside HTML and CSS to build both simple and complex web applications. This course offers a comprehensive introduction to JavaScript for beginners, starting with fundamental concepts like problem-solving and simple JavaScript programs. Through interactive exercises, challenges, and quizzes, learners will master control structures, loops, strings, arrays, and functions. By the end of this course, you'll have solid problem-solving skills, a deep understanding of JavaScript programming, and practical experience in writing clean, efficient code. This knowledge will prepare you for a successful career as a JavaScript developer and significantly enhance your employability in the tech industry.

8hrs
Beginner
4 Challenges
4 Quizzes

Introduction to JavaScript Loop#

A loop is a control structure that allows a code block to execute repeatedly until a specified condition is met. It automates repetitive tasks. Imagine processing 1,000 user records: writing 1,000 lines of code isn’t just tedious—it’s error-prone. With loops, you can solve this in just three lines.

To see how useful loops are, let’s consider the following code snippets:

Javascript (babel-node)
// program to serve customers until there are none left in the queue
let customersLeft = 10;
function serve() {
// custom code to fulfil customer’s order
console.log('Finished serving a customer.');
}
serve();
serve();
serve();
serve();
serve();
serve();
serve();
serve();
serve();
serve();

We would have to repeat the call to serve() several times without a loop. This approach is impractical for larger tasks, such as serving 1,000 customers.

Let’s rewrite the above program, but we will use the for loop to make some improvements this time.

Javascript (babel-node)
// program to serve customers until there are none left in the queue
let customersLeft = 10;
function serve() {
// custom code to fulfil customer’s order
console.log("Finished serving customer.");
}
for (let index = 0; index < customersLeft; index++) {
serve(); // this would be executed 10 times
}

We can still invoke the serve() function 10 times using a for loop in the above code. Additionally, when the number of customers changes, we have to update the value of customersLeft. This improves maintainability and scalability.

How does a loop work?#

Like most programming languages, loops in JavaScript allow us to execute a statement or block of code repeatedly based on a condition. Each loop consists of the following key components:

  • Initialization: This is the starting point for declaring and setting the loop variable. It runs once before the loop begins. For example, let i = 0 initialize a counter at 0.

  • Condition: A boolean expression determining whether the loop should continue running (e.g., i < 10).

  • Increment: Modifies the loop variable after each iteration (e.g., i++).

  • Code block: The set of instructions that executes as long as the condition remains true.

Structure of a loop#

A loop typically follows this structure in JavaScript:

LOOP (condition) {
// loop body
}
Syntax of a loop

Here’s how it works:

  1. The loop starts with a loop keyword (such as for, while, or do...while).

  2. The condition inside the parentheses is evaluated before each iteration. If it evaluates to true, the loop executes the code block.

  3. Once the condition becomes false, the loop terminates.

Let’s visualize the flow of a loop below:

Flow structure of a loop
Flow structure of a loop

Types of loop in JavaScript#

JavaScript offers several types of loops, each suited for specific scenarios. Here’s an overview:

  • for: Executes a block of code a specific number of times.

  • while: Runs a block of code while a condition is true.

  • do...while: Similar to the while loop but guarantees at least one execution.

  • for...in: Iterates over the properties of an object.

  • for...of: Iterates over the values of an iterable object (e.g., arrays).

Let’s explore each of these in detail.

1. The for loop#

The for loop is the most commonly used loop in JavaScript. It has three parts:

  • Initialization: Executed once before the loop starts.

  • Condition: Evaluated before each iteration. If true, the loop continues.

  • Increment/Decrement: Executed after each iteration.

Here’s the syntax:

for (initialization; condition; increment) {
// Code to execute
}
The syntax of the for loop

Let’s execute an example of the for loop.

Javascript (babel-node)
for (let i = 0; i < 5; i++) {
console.log(i); // Prints numbers 0 to 4
}

Do you know?

Brendan Eich created JavaScript in just 10 days in 1995, and the for loop has been around since then!

2. The while loop#

The while loop executes a code block if a condition is true. It’s ideal when the number of iterations isn’t known in advance.

Here’s the syntax:

while (condition) {
// Code to execute
}
The syntax of the while loop

Let’s execute an example of the while loop.

Javascript (babel-node)
let num = 0;
while (num < 5) {
console.log(num); // Prints numbers 0 to 4
num++;
}

Be cautious with while loops—if the condition never becomes false, the loop will run indefinitely.

3. The do...while loop#

The do...while loop is similar to the while loop but ensures the code block runs at least once, even if the condition is initially false.

Here’s the syntax:

do {
// Code to execute
} while (condition);
The syntax of the do...while loop

Let’s execute an example of the do...while loop.

Javascript (babel-node)
let num = 0;
do {
console.log(num); // Prints numbers 0 to 4
num++;
} while (num < 5);

Do you know?

The do...while loop is a relic of structured programming, dating back over 50 years, and it remains a small but interesting part of JavaScript today!

Comparison: while vs. do...while#

Both while and do...while loops execute a block of code repeatedly as long as a specified condition remains true. However, there is a key difference in how they check the condition.

Features

The while Loop

The do-while Loop

Condition check

Before loop starts

After the loop executes at least once

Minimum runs

0 (if the condition is false)

1 (always runs at least once)

Best use case

When you may not need to run the loop at all

When you need at least one guaranteed iteration

4. The for...in loop#

The for...in loop iterates over an object’s enumerable properties, making it ideal for working with key-value pairs.

Here’s the syntax:

for (const key in object) {
// Code to execute
}
The syntax of the for...in loop

Let’s execute an example of the for...in loop.

Javascript (babel-node)
const user = { name: "ABC", age: 28, role: "Designer" };
for (const property in user) {
console.log(`${property}: ${user[property]}`);
}

Do you know?

for...in loops don’t just iterate over an object’s own properties; they include inherited ones too! That’s why Object.hasOwn() or Object.keys() are often safer choices.

5. The for...of loop#

The for...of loop iterates over iterable objects (arrays, strings, etc.), providing direct access to values rather than indexes.

Here’s the syntax:

for (const value of iterable) {
// Code to execute
}
The syntax of the for...of loop

Let’s execute an example of the for...of loop.

Javascript (babel-node)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color.toUpperCase());
}

You can loop over a string!
Strings are iterable, so you can use a for...of loop to iterate through characters.

Comparison: for...in vs. for...of#

Both for...in and for...of loops iterate over elements, but they serve different purposes.

  • The for...in loop iterates over an object’s keys (property names), including inherited properties from the prototype chain. Because of this, it is not recommended to iterate over arrays unless filtered using hasOwnProperty.

  • The for...of loop is used to iterate over values of iterable objects like arrays, strings, maps, and sets. It does not work on plain objects unless converted into an iterable structure.

Here is a comparison table between for...in and for...of loops.

Feature

for...in

for...of

Iterates over

Object property keys

Iterable values (arrays, strings, maps, sets)

Works with objects?

Yes

No (unless converted to an iterable)

Works with arrays?

Yes (but it includes inherited properties, so not recommended)

Yes

Returns

Property names (keys)

Values

Best use case

Iterating over object properties (use hasOwnProperty to exclude inherited ones)

Iterating over elements of an array, string, or iterable

Do you know?
Older versions of JavaScript had a for each...in loop for iterating over object values, but it was removed in ES6 in favor of for...of.

Performance considerations:

  • Avoid infinite loops by ensuring loop conditions eventually become false.

  • Prefer for...of for iterating over arrays instead of for...in.

  • Minimize nested loops to prevent performance degradation.

6. The forEach() method#

The forEach() method is a built-in array function that executes a provided callback function once for each array element. While not a traditional loop, it’s widely used for iterating over arrays.

Here’s the syntax:

array.forEach((element, index, array) => {
// Code to execute
});
The syntax of the forEach() method

Let’s execute an example of the forEach() method.

Javascript (babel-node)
const numbers = [1, 2, 3];
numbers.forEach((num) => {
console.log(num * 2); // Output: 2, 4, 6
});

The .forEach() method lacks support for break or continue because its callback runs on every element without exposing loop control. Use a for...of or traditional for loop when you need to interrupt or skip iterations.

Which loop to use?#

Choosing the right loop in JavaScript depends on the data structure you are working with and what you need to accomplish. Here’s a guide to when to use each of the common loops in JavaScript:

  • The for loop is a deal when you need to iterate a specific number of times or when you have an index that controls the loop’s execution.

  • Use a while loop when you want to run a loop until a specific condition is no longer true, and you may not know the exact number of iterations upfront.

  • The do-while loop is useful when you want the loop to run at least once.

  • Use the for...in loop to iterate over the enumerable properties of an object, including inherited properties from the prototype chain.

  • The for...of loop is best for iterating over iterable objects like arrays, strings, or sets.

  • Use forEach() for simple array iteration when you don’t need to break or return a new array.

Loop Type

Best Used When

Avoid When

Use Case

for

The exact number of iterations needed is known

The number of iterations is uncertain

Iterating through array indexes

while

The number of iterations is not fixed

The exact count is known beforehand

Processing user input until valid

do-while

At least one iteration is required

You might not want any iterations

Input validation with retry logic

for...of

To iterate over array values directly

You need the index or need to modify the array

Reading values from an array

for...in

To iterate over object properties

Working with arrays (can include prototype properties)

Iterating through object keys

forEach()

Cleaner syntax for array operations is needed

You need to break/continue or need async operations

Simple array transformations

Do you know?
In older JavaScript engines, looping backward (for (let i = arr.length - 1; i >= 0; i--)) was often faster because it avoided unnecessary length recalculations. Modern engines optimize this now.

Nested loops#

A nested loop is simply a loop inside another loop. This structure is useful when dealing with multidimensional data, such as tables or matrices, or when performing repetitive tasks requiring multiple iteration levels.

Here’s the syntax of a nested loop using the for loop:

for (let i = 0; i < outerLimit; i++) { // Outer loop
for (let j = 0; j < innerLimit; j++) { // Inner loop
// Code to execute
}
}
The syntax of a nested loop

Each iteration of the outer loop triggers a full cycle of the inner loop. This means that for every single execution of the outer loop, the inner loop runs completely.

Do you know?

Nested loops originated in early programming languages like FORTRAN (1957) and ALGOL (1960), where they were used for handling multidimensional arrays and matrix operations.

Example: 2x2 matrix multiplication using nested loops

Matrix multiplication involves multiplying rows of one matrix with columns of another. In a 2×22\times 2 matrix, each element in the resulting matrix is computed as the sum of the product of corresponding elements from the row of the first matrix and the column of the second matrix.

Javascript (babel-node)
const matrixA = [[1, 2], [3, 4]]; // 2x2 matrix
const matrixB = [[5, 6], [7, 8]];
const result = [[], []];
// Multiply two matrices
for (let rowA = 0; rowA < matrixA.length; rowA++) { // Current row in Matrix A
for (let colB = 0; colB < matrixB[0].length; colB++) { // Current column in Matrix B
let sum = 0;
for (let elementIndex = 0; elementIndex < matrixA[0].length; elementIndex++) { // Element position
sum += matrixA[rowA][elementIndex] * matrixB[elementIndex][colB];
}
result[rowA][colB] = sum;
}
}
console.log(result); // [[19, 22], [43, 50]]

Key considerations while using nested loops#

  • Performance: Nested loops have polynomial time complexity—avoid large datasets.

  • Variable naming: Use descriptive names like row/col instead of i/j for clarity.

  • Break/Continue: Use cautiously—break in inner loops only exits the innermost loop.

Enhance your JavaScript expertise—dive into our course on mastering data structures and sorting algorithms for a hands-on learning experience that elevates your coding skills.

Cover
Mastering Data Structures and Sorting Algorithms in JavaScript

Are you ready to become a top-notch JavaScript developer? Understand two of the most important concepts in programming - Data Structures & Sorting Algorithms. Learn to make efficient algorithms that save space and time if you want to excel in the field of software development. Take this interactive course to find out how to employ the most effective data structure in any scenario. This course covers sorting algorithms and their time complexity using JavaScript along with various data structures like Trees, Graphs, Heaps, Linked lists and many more.

3hrs
Beginner
34 Playgrounds
304 Illustrations

Controlling loops: break and continue#

JavaScript provides the break and continue statements to control loop execution effectively.

The break statement#

The break statement exits a loop before it completes all iterations. This is useful when a certain condition is met, and continuing further iterations is unnecessary.

Javascript (babel-node)
for (let i = 1; i <= 10; i++) {
if (i === 5) break;
console.log(i);
}
// Output: 1, 2, 3, 4

In this example, the loop terminates when i reaches 5.

Do you know?
The break statement in JavaScript originates from C (1972), where it was used to exit switch statements and loops.

The continue statement#

The continue statement skips the current iteration and moves to the next one. This is useful when specific conditions require skipping certain values while continuing execution.

Javascript (babel-node)
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
// Output: 1, 2, 4, 5 (3 is skipped)

In this example, when i equals 3, the continue statement prevents further execution for that iteration and moves to the next value.

Tip: Use break and continue wisely to improve loop efficiency and readability, making your code more structured and purposeful.

How to use loops in practice#

Loops are incredibly useful for handling arrays, objects, and other iterable data structures. Below are two practical examples of using loops in real-world scenarios.

Rendering a list of items in HTML#

When working with the DOM, loops help dynamically generate content.

Example: Rendering a list of items in HTML

This uses forEach to loop through an array and dynamically add list items (<li>) to the page.

Filtering even numbers from an array#

You may need to filter data based on a condition, such as finding even numbers in an array.

Javascript (babel-node)
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push(numbers[i]);
}
}
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]

The for loop iterates over an array, checks if each number is even, and stores it in a new array.

What to learn next#

Congratulations on mastering loops! Loops are a powerful tool that helps improve code efficiency and readability. To further strengthen your understanding, here are some next steps:

  • Conditional loops: Learn how conditions inside loops affect execution, such as while and do-while loops.

  • Nested loops: Understand how loops within loops work and when to use them efficiently.

  • Infinite loops: Identify and avoid infinite loops that can crash programs.

  • Loop time complexities: Learn how different loops affect performance and efficiency in big data processing.

  • Advanced iterators: Explore modern alternatives like .map(), .reduce(), and .filter() for working with arrays.

This article only covers the basics of Loops in JavaScript. To continue learning, check out the following project-based course that covers every part of JavaScript. Once you finish this course, you will have an advanced grasp of the language and be ready to tackle more advanced projects.

Cover
JavaScript in Detail: From Beginner to Advanced

In this project-based course you will dissect every part of JavaScript from beginning concepts to more advanced. You will start by running through JS fundamentals such as arrays, types, variables, and conditional statements. You’ll then move on to more advanced concepts like OOP, regular expressions, and asynchronous programming. Throughout this course, you will be tasked with 4 projects that will test different parts of your understanding. At the end you will take a final exam to really hammer in what you’ve learned. Once you finish this course, you will have an advanced grasp of the language and you will be ready to tackle more advanced projects. Plus you’ll have some great intro projects to add to your portfolio.

12hrs
Beginner
20 Challenges
14 Quizzes

Frequently Asked Questions

How many types of loops are in JavaScript?

There are four main types of loops in JavaScript:

  1. for loop
  2. while loop
  3. do...while loop
  4. Iteration loops (for...in and for...of)

What is a loop() function?

JavaScript does not have a built-in loop() function, but you can create one using recursion:

function loop(n) {
    if (n <= 0) return;
    console.log(n);
    loop(n - 1); // Recursive call
}

loop(5);

This function acts like a loop by calling itself repeatedly.

When to avoid forEach() due to async limitations

When working with asynchronous operations, avoid using forEach() when you need to control the execution order or ensure that each asynchronous task is completed before starting the next one. Here are the key points:

  • No await support: forEach() does not wait for asynchronous operations (promises) to resolve. Even if you mark the callback as async, the loop will not pause for each promise.
  • Sequential execution issues: If your code depends on sequential processing (i.e., each asynchronous operation must complete before the next starts), forEach() won’t provide that behavior. Instead, use a for...of loop, which allows using await properly.
  • Error handling and early exit: forEach() doesn’t allow for breaking out of the loop early (like using break in a for loop) or catching errors straightforwardly with try/catch in an asynchronous context.

What are the alternatives to forEach() due to async limitations?

forEach() does not handle asynchronous operations well because it does not wait for promises to resolve. Here are several alternatives that work better with async operations:

  • for-of loop: This loop works seamlessly with async/await and allows you to handle each asynchronous task sequentially.

    for (const item of array) {
      await asyncOperation(item);
    }
    
  • Traditional for loop: Like for...of, a classic for loop provides full control over loop execution and supports async/await.

    for (let i = 0; i < array.length; i++) {
      await asyncOperation(array[i]);
    }
    
  • Promise.all with Array.map: If order isn’t important and you want to run all asynchronous operations concurrently, you can map your array to promises and use Promise.all.

    await Promise.all(array.map(item => asyncOperation(item)));
    
  • Array.reduce for sequential execution: A functional approach where you chain promises sequentially using reduce.

    await array.reduce((prevPromise, item) => {
      return prevPromise.then(() => asyncOperation(item));
    }, Promise.resolve());
    

Each of these alternatives is suited to different scenarios—choose the one that best meets your needs regarding sequential vs. concurrent execution and error handling.

What is the difference between forEach() and map()?

forEach():

  • Iterates over each element.
  • Executes a provided function mainly for side effects (e.g., logging, DOM manipulation).
  • Does not return a new array—it always returns undefined.

Example:

const numbers = [1, 2, 3];

// Using forEach()
numbers.forEach(num => console.log(num * 2)); // Logs 2, 4, 6 (No return)

map():

  • Iterates over each element.
  • Applies a function to transform each element.
  • Returns a new array with the transformed values; the original array remains unchanged.

Example:

const numbers = [1, 2, 3];

// Using map()
const doubled = numbers.map(num => num * 2); // Returns [2, 4, 6]
console.log(doubled);

Quick tip:

  • Use forEach() for side effects (like logging or updating the DOM).
  • Use map() when you need a new transformed array.


Written By:
Rauf Tabassam

Free Resources