There are four main types of loops in JavaScript:
for
loopwhile
loopdo...while
loop- Iteration loops (
for...in
andfor...of
)
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
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.
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:
// program to serve customers until there are none left in the queuelet customersLeft = 10;function serve() {// custom code to fulfil customer’s orderconsole.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.
// program to serve customers until there are none left in the queuelet customersLeft = 10;function serve() {// custom code to fulfil customer’s orderconsole.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.
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
.
A loop typically follows this structure in JavaScript:
LOOP (condition) {// loop body}
Here’s how it works:
The loop starts with a loop keyword (such as for
, while
, or do...while
).
The condition inside the parentheses is evaluated before each iteration. If it evaluates to true
, the loop executes the code block.
Once the condition becomes false
, the loop terminates.
Let’s visualize the flow of a loop below:
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.
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}
Let’s execute an example of the for
loop.
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!
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}
Let’s execute an example of the while
loop.
let num = 0;while (num < 5) {console.log(num); // Prints numbers 0 to 4num++;}
Be cautious with while
loops—if the condition never becomes false
, the loop will run indefinitely.
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);
Let’s execute an example of the do...while
loop.
let num = 0;do {console.log(num); // Prints numbers 0 to 4num++;} 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!
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 | The |
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 |
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}
Let’s execute an example of the for...in
loop.
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.
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}
Let’s execute an example of the for...of
loop.
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.
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 |
|
|
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 | 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.
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});
Let’s execute an example of the forEach()
method.
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.
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 |
| The exact number of iterations needed is known | The number of iterations is uncertain | Iterating through array indexes |
| The number of iterations is not fixed | The exact count is known beforehand | Processing user input until valid |
| At least one iteration is required | You might not want any iterations | Input validation with retry logic |
| To iterate over array values directly | You need the index or need to modify the array | Reading values from an array |
| To iterate over object properties | Working with arrays (can include prototype properties) | Iterating through object keys |
| Cleaner syntax for array operations is needed | You need to | 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.
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 loopfor (let j = 0; j < innerLimit; j++) { // Inner loop// Code to execute}}
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
const matrixA = [[1, 2], [3, 4]]; // 2x2 matrixconst matrixB = [[5, 6], [7, 8]];const result = [[], []];// Multiply two matricesfor (let rowA = 0; rowA < matrixA.length; rowA++) { // Current row in Matrix Afor (let colB = 0; colB < matrixB[0].length; colB++) { // Current column in Matrix Blet sum = 0;for (let elementIndex = 0; elementIndex < matrixA[0].length; elementIndex++) { // Element positionsum += matrixA[rowA][elementIndex] * matrixB[elementIndex][colB];}result[rowA][colB] = sum;}}console.log(result); // [[19, 22], [43, 50]]
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.
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.
JavaScript provides the break
and continue
statements to control loop execution effectively.
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.
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 skips the current iteration and moves to the next one. This is useful when specific conditions require skipping certain values while continuing execution.
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.
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.
When working with the DOM, loops help dynamically generate content.
This uses forEach
to loop through an array and dynamically add list items (<li>
) to the page.
You may need to filter data based on a condition, such as finding even numbers in an array.
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.
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.
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.
How many types of loops are in JavaScript?
What is a loop()
function?
When to avoid forEach()
due to async limitations
What are the alternatives to forEach()
due to async limitations?
What is the difference between forEach()
and map()
?
Free Resources