Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: August 11, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

JavaScript is among the most-used programming languages. Developers that intend to become JavaScript engineers must learn the basics of loops, their types, and how they work. 

A JavaScript loop is a tool used to perform repeated tasks based on a certain condition. On the other hand, ‘iterate’ is a generic term, meaning repeat in the context of the loop. A loop will continue to iterate until a stopping condition is met. 

To understand it better, you can think of it as a computerized game where you are instructed to take X steps northwards and then Y steps to the left. 

You can represent take 7 steps northwards as; 

for (let step = 0; step < 7; step++) {

  // Runs 7 times, with values of steps 0 through 6.

  console.log("Walking northwards one step");

}

when the above block of code is executed, you will have this;

image-144

Why are loops usually used?

  • Perform repetitive tasks: You can use loops to execute instructions until certain conditions are met. 
  • Iterate over objects or arrays: With loops, you can iterate over properties of an object or elements of an array, allowing you to perform certain actions for each property or element. 
  • Filter data: You can use a loop to filter data based on specific conditions. 

JavaScript loops come in different forms; For, While, Do...While, For...of, and For...in. Let us explore them in detail and demonstrate how each works. 

For loop

A for loop will repeat until a specified condition evaluates to true. A for loop has three optional expressions, followed by a code block. 

for (initialization; condition; finalExpression) {

  // code

}
  • The initialization expression comes before the first loop is executed. This expression usually initializes one or more counters. 
  • A condition expression is checked on every time before the for loop runs. The code in the loop or statement executes every time the expression evaluates to true. On the other hand, the loop stops when the expression evaluates to false. However, if the expression is omitted, the expression will evaluate to true automatically. 
  • The finalExpression executes after each loop iteration. The expression is mostly used to increment a counter.

You can use {}, block statement, to group and execute multiple statements. If you want to exit the loop early before the condition expression evaluates to false, use the break statement. 

Examples of for loops with code 

  1. Use for loop  to iterate;
for (let i = 0; i < 7; i++) {

  console.log(i);

}

In this code block;

  • The variable i is initialized to zero (let i=0). 
  • The condition is i should be less than 7 (i=7). 
  • The loop will repeatedly iterate if the value of i is less than 7 (i<7>. 
  • The iteration will add 1 to the value of i after every iteration (++1). 
For-loop
  1. Use break statement to exit the loop before the condition evaluates to false;
for (let i = 1; i < 11; i += 2) {

  if (i === 9) {

    break;

  }

  console.log('Total developers: ' + i);

}
  • The code block iterates from 1 to 10 (i<11).
  • The loop initializes a variable i with a value of 1 (let i = 1). 
  • The loop condition will continue executing if the value of i is less than 11 (i < 11). 
  • The value of i increases by 2 after every iteration (i += 2). 
Break-statement

The if statement evaluates whether the value of i=9. If the condition is true, the break statement executes, and the loop terminates. 

(image)

For…of loop

The for…of loop iterates over iterable objects such as Map, Array, Arguments, and Set. This loop invokes a custom iteration hook with statements that execute for the value of each distinct property. 

The basic structure of a for…loop is;

for (variable of object)

  statement

Examples of for…of loop in action

  1. For…of loop iterating over an array
const frontendLanguages = [ "HTML", "CSS", "JavaScript" , “React”];

for (let i of frontendLanguages) {

  console.log(i);

}

In this code;

  • We define an array named frontendLanguages
  • The array has three elements; "HTML", "CSS",  "JavaScript" and “React”
  • The for…of loop iterates over each element in frontendLanguages.
  • The i in the code block takes up the value of each element during each iteration and the values printed on the console. 
Forof-Array
  1. For…of loop iterating over a Set
const s = new Set();

s.add(2);

s.add("grey");

for (let n of s) {

  console.log(n);

}

In this block of code;

  • We declare a variable s, which we assign to a new Set using the Set() constructor.
  • Two elements are added to the code using add() method
  • The for….of iterates over the elements object.
  • The loop assigns the current element to n before executing console.log(n) statement. 
Forof-Set
  1. For…of loop iterating over a Map
const m = new Map();

m.set(4, "rabbit");

m.set(6, "monkey");

m.set(8, "elephant");

m.set(10, "lion");

m.set(12, "leopard");

for (let n of m) {

  console.log(n);

}

In this code block;

  • We use Map() constructor to create a new Map object.
  • A variable m is declared.
  • Using .set() method, we add five key-value pairs.
  • A for…of loop iterates over elements of Map object m. 
Forof-Map

For…in loop

A for…in loop is used to iterate over the properties of an object. The basic structure of a for…in loop is;

for (property in object) {

  // code

}

You can use for…in loop to iterate over arrays and array-like objects

const shoppingList = { kales: 4, tomatoes: 2, cabbage: 0, lettuce:6, pumpkin:5 };

for (const vegetable in shoppingList) {

  console.log(vegetable);

}

In this code block;

  • We introduce a JavaScript object and name it shoppingList
  • We use for loop to iterate over each property on the shoppingList using the in operator. 
  • In each iteration, the loop assigns the current property name in the shoppingList
image-145

While

The while loop evaluates a condition, if it finds it to be true, the code block executes. However, if the condition is false, the loop ends, and the code block will not be executed.

This is the basic structure of a while loop;

 

while (condition)

    Statement

The test condition must occur before the execution of the statement in the loop. You can execute multiple statements using {} or block statements. 

Example of while loop in action

let n = 0;

while (n < 9) {

  console.log(n);

  n++;

}

In this code;

  • A variable n is initialized with a zero value (let n=0).
  • The loop will execute as long as the value of n is less than 9 (n<9)
  • The value of n is displayed on the console and increased by 1 after every iteration (n++)
  • The code will stop executing at 8. 
While

Do … While Loop

A do…while loop iterates until a specific condition evaluates to false

The general structure of a do…while statement is;

do

  statement

while (condition);

The statement is executed once but before checking the condition. The statement will execute if the condition is true. However, if the evaluated condition is false, execution will stop, and the control passes to the statement after the do..while. Code in a do…while loop is guaranteed to run at least once, even if the condition evaluates to true

Example of do…while

let n = 0;

do {

  n += 1;

  console.log(n);

} while (n < 7);

In this code;

  • We introduce a variable n and set its initial value as 0 (let n=0).
  • Our variable n enters a do…while loop where its value is incremented by 1 after every iteration (n+=1)
  • The value of n is logged.
  • The loop will continue to execute as long as the value of n is less than 7 (n<7). 

When you run this code, the console will show values of n starting from 1 to 7 as the loop executes 7 times.

Do-While

Nested Loop

A nested loop is a situation whereby we have a loop inside a loop. For instance, we can have a for loop nested inside another for loop. 

for (let outer = 0; outer < 5; outer += 2) {

  for (let inner = 0; inner < 6; inner += 2) {

    console.log(`${outer}-${inner}`);

  }

}
  • There are two variables; outer and inner and both are initialized with the value zero.
  • Both variables are incremented by 2 after every iteration
  • The outer and inner loops iterate three times each. 
image-146

Loop control statements

Loop control statements, sometimes known as “jump statements” interrupt the normal flow of a program. Break and continue are examples of loop control statements.

Break statements

Break statements terminate a loop immediately, even if the condition has not been fulfilled. 

for (let n = 1; n <= 26; n++) {

  if (n === 13) {

    console.log("Loop stops here. We have reached the break statement");

    break;

  }

  console.log(n);

}

The rendered code will appear as;

image-147

Continue statements

Continue statements are used to skip a certain block of code and carry out iteration for the new loop. 

for (let n = 0; n <= 10; n++) {

  if (n === 5) {

    continue;

  }

  console.log(n);

}

The rendered code will appear as;

image-148

Conclusion

Above are the common loops you will come across in vanilla JavaScript and its frameworks/ libraries. As highlighted, each loop type has its use case and different behaviors. If you pick the wrong loop type, you will likely have bugs, and your code will likely display unexpected behavior. 

If you are dealing with a JavaScript framework or library, always check its documentation and use the built-in loops. 

  • Titus Kamunya
    Author
    Titus is a Software Engineer and Technical Writer. He develops web apps and writes on SaaS, React, HTML, CSS, JavaScript, Ruby and Ruby on Rails read more
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder