JavaScript loops

All types of loops in JavaScript | brief explanation | examples

A loop is a mechanism in computer programming that repeats a specific block of code for a true condition. Loops are a quick and straightforward way to repeat something. This chapter of the JavaScript Guide introduces JavaScript’s different loop statements.

In JavaScript, there are several different types of loops. We’ve put them in an order that will help you understand how they work and how to use them. This post will also assist you in differentiating between all of these loops, such as where, when, and how to apply them. So let’s get started.

  • while
  • do-while
  • for
  • for…in
  • for…of

While loop

While loops are one of the most fundamental types of loops available in Javascript. If JavaScript isn’t the single language you’re familiar with, you’ve probably heard of this one.

The while loops are the simplest type of iteration. They look like the following:

// syntax of while loop
while (condition) {

// your code

 }


// example of js while loop
let i = 0;
 while (i < 10) {

     i++;

 }

The while statement creates a loop that executes over a certain block of code as long as the condition is true. The condition is verified each time and the block of code is executed.

For example, this loop will execute the block of code inside curly brackets until the variable is smaller than 5.

let i = 0;
 while (i < 5) {

     console.log(`i is equal to ${i}`);
     i++;

 }

// i is equal to 0
// i is equal to 1
// i is equal to 2
// i is equal to 3
// i is equal to 4

Hence the 5 == 5 but not smaller than 5 so the execution will stop when i will be equal to 5.

Do-while loops

The do…while loops are a variation of the while loop. As an example, consider the following:

// syntax
do {

    //Block of code...

 }
while (condition);

// an example
let i = 0;

 do {

   i++;

 } while (i < 5);

Here the do statement is followed by a code block, which is followed by a condition. This means that before the condition is evaluated, the code block is always executed at least once.

look at the following example:

let i = 0;
 do {
      i++;
     console.log(`i equal to ${i}`);

 } while (i < 0);

// i equal to 1

As you can see the value of the variable i is initially zero. we are incrementing it by one inside the body of the loop. The condition is false now but this block of code will still print i equal to 1 at least one time.

For loops

The for loop is the most commonly used type of loop.

The while loop and the for loop work identically, and their execution times are not much different.
In the case of a for loop, the definition and initialization of looping variables, condition checks, and increments and decrements of looping variables can all be done on the same line. It improves readability and minimizes the likelihood of error.

//syntax
for ([initialization];[condition];[increments-or-decrements]){

   // Block of code

}

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

    console.log(`value of i is ${i}`);

}

// value of i is 0
// value of i is 1
// value of i is 2
// value of i is 3
// value of i is 4

for…in loop

The for…in loop is used to iterate over the elements of an array or an object. It can only be used for this purpose. It cannot be used as a general-purpose repetition mechanism to replace for loop or while loop.

Let’s look at an example of how to use a for-in loop to loop through the items of an array. However, keep in mind that this is primarily for informational purposes, as for…in is best suited for objects while the conventional for loop is best suited for arrays.

In this example, you may iterate through all of the items of an array and print out the index (the key) and value of each element, such as:

const alphabets = ['a', 'b', 'c', 'd', 'e', 'f'];

for (var i in alphabets) {

 console.log(`key = ${i} - value = ${alphabets[i]}`);

 }

// key = 0 - value = a
// key = 1 - value = b
// key = 2 - value = c
// key = 3 - value = d
// key = 4 - value = e
// key = 5 - value = f

The for…of loop

This is the most recent looping type in Javascript, having been introduced in ES6. You can iterate through an iterable object with the for…of statement, such as an Array, String, Map, WeakMap, Set, WeakSet, arguments object, TypedArray, and even general objects.

For example, we will iterate the string with for…of:

let str = 'abcd';

for(value of str) {

console.log(value);

}

// a
// b
// c
// d

Conclusion

In JavaScript, loops are used to perform repeated tasks based on a condition. Typically, conditions return true or false. A loop will continue to run until the specified condition returns false.

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

Read more: JavaScript rest and spread operators.

Add comment