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

JavaScript Loops Tutorial: for loop, while loop, and more

7 min read
Nov 12, 2020

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.

Loops are used in programming to perform a specified task repeatedly based on a condition. They provide control over iterative tasks and help improve code readability. They are a fundamental part of many programming languages and should be a part of every developer’s toolkit.

In this tutorial, we’ll focus on loops in JavaScript. Each programming language is different when it comes to looping.

By the end of the article, you should be familiar with working with JavaScript loops. You would also have learned about the important gotchas and scenarios where loops are helpful.

Today we will learn:



Learn how to build with JavaScript

This project-based dissects every part of JavaScript from beginner to advanced concepts. Once you finish this course, you will have built 4 projects from scratch.

JavaScript in Detail: From Beginner to Advanced



Introduction to Loops#

Introduction to Loops

A loop is a programming structure that allows a statement or block of code to be run repeatedly (iterate) until a specified condition is no longer true (will return Boolean, true or false). It is one of the most powerful and fundamental programming concepts.

Simplified: A loop is a programming structure that repeats a sequence of instructions until a specific condition is met.

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

// program to serve customers until there are none left in the queue
let customersLeft = 10;
function serve() {
// arbitrary code to fulfil customer's order
console.log('finished serving customer');
}
serve();
serve();
serve();
serve();
serve();
serve();
serve();
serve();
serve();
serve();

Without utilizing a loop, we would have to repeat the call to serve() a number of times. This becomes unsustainable when the number of customers increases to 1,000.

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

// program to serve customers until there are none left in the queue
let queue = 10;
function serve() {
// arbitrary code to fulfil customer's order
console.log("finished serving customer");
}
for (let index = 0; index < queue; index++) {
serve(); // this would be executed 10 times
}

Note that we are still able to invoke the serve() function 10 times. Additionally, when the number of customers changes, all we have to do is update the value of customersLeft.

Now we will take a closer look at loops in JavaScript. By the end, you should be able to know the different types of loops in JavaScript and when to use each one.


Types of loops in JavaScript#

Like most other programming languages, JavaScript provides loops that help us execute a statement or block of code repeatedly. A loop usually has the following properties:

  • A condition which can be true or false
  • A program block that is executed while the condition is true

Below shows an outline of a loop in JavaScript:

svg viewer

The loop starts with a LoopToken token, followed by a condition in parentheses, and concludes with a set of instructions encapsulated within the brackets.

In the program we wrote earlier, the for statement is a LoopToken. For the condition, we initialize a counter at 0 and increment its value by 1 until it is greater than the value in the queue. Then we run the code within the brackets while this value is less than the queue.

The for loop is just one of the types of loops available. JavaScript supports different kinds of loops:

  • for: loops through code a number of times
  • for/in: loops through the properties of an object
  • while: loops through a block of code while a condition is true
  • for/of: loops through the values of an iterable object
  • do/while: loops through code while a condition is true

for Loop#

This is the most commonly used loop. A for loop loops through code a number of times. It has the following syntax:

for (begin; condition; step) {
  // statement(s) to execute
}

The begin part is executed once upon entering the loop. The condition is checked once for every iteration of the loop. If it’s false, the loop ends. If it’s true, the statement(s) will be executed and afterwards the step part is executed.

Simplified:

The initialization statement is executed before the loop starts.

The middle condition determines whether or not the loop will run a next iteration.

The last statement is executed each time after the loop has executed.

We’ve already seen the for loop in action earlier. See if you can modify the following code to print numbers from 1 to 5. Check the solution if you get stuck.

for (let i = 0; condition; i++) {
// print a number
}

Nested for loops#

Loops can contain other loops. Consider the following example:

for(var i = 0; i < 5; i++) {
console.log("Outer Loop Iteration:", i);
for(var j = 0; j < 5; j++) {
console.log("\tInner Loop Iteration:", j);
}
}

In this example, the inner loop will run five times for every iteration of the outer loop.

The first loop is typically called the outer loop, and the second loop is the inner loop. The outer loop executes first, and the inner loop executes each time the outer loop executes.


while Loop#

In a while statement, if the given condition is true, the code block will execute. The while loop has the following syntax:

while (condition) {
 // code to execute
}

While the condition is true (evaluates to a truth value), the statement(s) in brackets will be executed. Let’s look at an example.

var num = 0;
while(num <= 10) {
if(num !== 10) {
console.log("The number is", num, "- less than 10");
} else {
console.log("The number is", num, "- the loop is now over");
}
num++;
}

When working and iterating with while loops, it’s important to ensure that the condition evaluates to a false value. While loops can run indefinitely if not given a way to terminate the loop.

We must increment num at the end of the code block, so the while loop’s condition eventually becomes false.


do…while Loop#

The do…while loop is similar to the while loop, but they loop code while a condition is true. It has the following syntax:

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

This loop is typically preferred to the while loop when we want our statement(s) to execute at least once, regardless of the condition being truthful.



Keep the learning going.#

Learn JavaScript hands-on without scrubbing through videos or documentation. Educative’s text-based courses are easy to skim and feature live coding environments - making learning quick and efficient.

JavaScript in Detail: From Beginner to Advanced



while Loops vs. do…while Loops#

We’ve seen that while Loops and do...while Loops are similar. When a do...while loop is used, the statement(s) gets executed at least once before the condition is checked truth/false. To illustrate this, consider the following code snippet:

let count = 5;
do {
console.log("hello world!");
// will run at least once
// because the condition check comes after the code statement
} while (count < 5);
while (count < 5) {
console.log("hello world");
// never runs because the condition is false
}

Another important thing to note while using either loop is that, unlike in a for loop, the step part needs to be inside the statement block. Let’s demonstrate this with the following example.

First, we’ll modify the program from earlier that serves customers in a queue:

// program to serve customers until there are none left in the queue
let queue = 10;
function serve() {
// arbitrary code to fulfil customer's order
console.log("finished serving customer");
}
while (queue > 0) {
serve(); // this will run infinitely
}

This loop will run forever because it has no control. We can fix this by making the following modification:

// program to serve customers until there are none left in the queue
let queue = 10;
function serve() {
// arbitrary code to fulfil customer's order
console.log("finished serving customer");
}
while (queue > 0) {
serve();
queue--; // step/control
}
/* do...while loop */
// do {
// serve();
// queue--;
// } while (queue > 0);

Let’s test our knowledge of while and do…while loops (and JavaScript arrays) using an exercise. We want to write a small program that will count to five in a do/while loop. Check the solution if you get stuck.

var count = // write your code here
do{
// write your code here
}while (count < )
console.log("Program has ended with count:", count);

Break and continue in loops#

Until now, our loops have run until the condition eventually evaluates to a false value. What if we want to exit the loop early, for example, under a special condition? We can achieve this using the break; statement.

The loop in the following code snippet will terminate at the fifth loop iteration, instead of the tenth iteration (without the break statement):

let index = 0;
for (; index < 10; index++) {
console.log("Hello!");
if (index == 5) {
// this will cause the program to skip the remaining iterations
// and run the statement outside this loop
break;
}
}
console.log("Loop stopped after " + index + " iterations");

If we want to skip just one iteration and continue the loop, we can use the continue; statement:

let index = 0;
for (; index < 10; index++) {
if (index == 5) {
continue;
// this will be skipped
}
console.log("This is iteration no. " + index);
}

How to use loops in practice#

Loops can be very handy when we find ourselves working with arrays and other iterable data structures and objects. The following are some scenarios where you would want to use loops in your code. Let’s look at two examples.


Rendering a list of items in HTML#

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<h1>To-do List</h1>
<ul id="list"></ul>
<script type="text/javascript">
const todoItems = [
"go for a run",
"take out the trash",
"go grocery shopping",
"prepare pasta",
"take the car for a wash",
];
let list = document.getElementById("list");
for (let index = 0; index < todoItems.length; index++) {
const item = todoItems[index];
const li = document.createElement("li");
li.innerHTML = "<p>" + item + "</p>";
list.append(li);
}
</script>
</body>
</html>

Implementing custom logic on an Array#

const arr = [
"a string",
2,
"another string",
{
text: "an object",
},
["a", "nested", "array"],
"last string",
];
const arrOfStrings = [];
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
if (typeof element === "string") {
arrOfStrings.push(element);
}
}
console.log(arrOfStrings);
// outputs [ 'a string', 'another string', 'last string' ]

What to learn next#

Congratulations on making it to the end! Utilizing loops in your code will help improve readability while allowing you to implement complex logic. Next, you should learn the following concepts:

  • Conditional Loops
  • Nested loops
  • Infinite loops
  • Loop time complexities and more

This article only covers the basics of Loops in JavaScript. To continue learning, check out Educative’s course JavaScript in Detail: From Beginner to Advanced. This is a project-based course that covers every part of JavaScript. Once you finish this course, you will have an advanced grasp of the language and you will be ready to tackle more advanced projects.

Happy learning!


Continue reading about JavaScript#


Written By:
Jerry Ejonavi
 
Join 2.5 million developers at
Explore the catalog

Free Resources