How to Write JavaScript Loops

Hey - Nick here! This page is a free excerpt from my $99 course JavaScript Fundamentals.

If you want the full course, click here to sign up and create an account.

I have a 30-day satisfaction guarantee, so there's no risk (and a ton of upside!) in signing up for this course and leveling up your JavaScript developer skills today!

In this tutorial, you will learn how to write JavaScript loops. Specifically, we will discuss how to write for, for of, for in, and while loops in the JavaScript programming language.

Table of Contents

You can skip to a specific section of this JavaScript tutorial using the table of contents below:

How to Write for Loops in JavaScript

The for loop is the most basic loop in computer science and is included in virtually every programming language. It is recognizable due to its use of the for keyword.

The general syntax of a JavaScript for loop is below:


for (statement) {

	action;

}

The for loop takes three conditions in its statement:

  1. initialExpression - an initial value for the variable we will be looping over.
  2. condition - a condition that is tested every time the loop is executed. The loop will continue as long as this condition evaluates to true.
  3. incrementExpression - an expression that changes the value of the initialExpression every time the loop is completed.

Each of these statements is separated by the ; character inside the round brackets of a for loop. Let’s add this logic to the generalized for loop that we saw previously:


for (initialExpression; condition; incremenExpression) {

	action;

}

Now, let’s create a for loop that prints “Nick” to the console 5 times.

To do this, the first thing we need to do is create our initial expression. In this case we will set i = 0 using the let keyword.


for (let i = 0; condition; incremenExpression) {

	action;

}

It is very important to use the let keyword inside of JavaScript loops and not the var or const keywords.

If you attempt to use the const keyword, then your loop will actually fail one its second pass when it tries to overwrite the const variable’s initial value.

If you use the var keyword, then your i variable will not be block-scoped and its value can leak out of the loop and cause bugs later in your program.

Next, we need to specify our condition, which will be i < 5.


for (let i = 0; i < 5; incremenExpression) {

	action;

}

Third, we need to increment the i variable with each pass of the loop. We can do this with an incrementExpression of i++.


for (let i = 0; i < 5; i++) {

	action;

}

Lastly, we need to add the console.log("Nick"); statement inside the loop block:


for (let i = 0; i < 5; i++) {

	console.log("Nick");

}

Note that you can actually use your increment variable i inside of the loop block. Specifically, you could print the different values of i to the console by making the following change to this loop:


for (let i = 0; i < 5; i++) {

	console.log(i);

}

The for loop is one of the most flexible loops in the JavaScript programming language, but it is also fairly heavy on syntax. We will learn simpler types of loops (that have less flexibility) later in this course, which may be useful for specific situations.

How to Write for of Loops in JavaScript

JavaScript’s for of loops are used to loop over iterables.

What is an iterable?

An iterable is anything that has a length - think strings, arrays, and similar data structures in JavaScript. In most cases, you will use the for of loop to work with strings or arrays.

Here is the generalized syntax of the for of loop:


for (const x of stringOrArray){

	action;

}

Let’s consider a few examples to see how the for of loop works in practice.

First, here is how you could use the for of loop to log every letter of a string to the console on a separate line:


const myName = 'Nick McCullum'

for (const letter of myName){

	console.log(letter);

}

Second, here’s how you could log every element of an array to the console using a for of loop in JavaScript:


const myArray = [0, 1, 2, 3, 4, 5]

for (let num of myArray){

	console.log(num);

}

How to Write for in Loops in JavaScript

The for in loop in JavaScript is used for looping over the keys of an object. For strings and arrays, this is the index of the character (for strings) or element (for arrays).

The syntax is identical to the for of loop, except you replace the of keyword with an in keyword.

Here is the generalized syntax of the for in loop:


for (const x of stringOrArray){

	action;

}

If we return to our previous example where we printed every character of my name on a separate line using the for of loop, the output is very different when using a for in loop instead. Here is the code:


const myName = 'Nick McCullum'

for (const letter in myName){

	console.log(letter);

}

My name has 13 characters (including the space). That means in this case, the loop will print the integers from 0 to 12, inclusive.

The for in loop has very specific use cases and it is hardly the most practical concept you’ll learn in this course. However, it is important to understand how they work as you may run into them in other developer’s code in the future.

How to Write while Loops in JavaScript

The while loop is used to continuously execute a JavaScript statement as long as a specified condition evaluates to true.

Here is the generalized syntax of a while loop in JavaScript:


while (condition){

	action;

}

Caution must be exercised when using while loops in JavaScript (or any other programming language). This is because it is possible to actually create infinite loops - which are blocks of code that can be executed indefinitely.

Tio avoid infinite loops, you must include some sort of increment statement inside the loop block. Here is an example:


let i = 0;

while (i < 5){

	console.log(i);

	I++; //This is the increment statement

	//Without the increment statement, this would create an infinite loop

}

Every while loop in JavaScript can be refactored into a for loop with some work. Said differently, while loops are not capable of solving any problems that can’t already be solved by for loops. Many developers prefer to use for loops because of this since they eliminate the possibility of accidentally creating an infinite loop.

Final Thoughts

In this lesson, you learned how to write loops in JavaScript. Specifically, we learned how to write four different types of loops:

  1. The for loop
  2. The for of loop
  3. The for in loop
  4. The while loop

These types of loops are fundamental parts of the JavaScript programming language, but they are not the most common ways that developers design iterable logic. We’ll learn about more common ways to create loops in JAvaScript in the next section.