Loops in JavaScript

Hey, everyone, welcome back, in this tutorial, you will get to know about loops in JavaScript and why you need to use the loop. In the previous tutorial, we have seen what conditional statements are in JavaScript. So, let’s begin.

Loops in JavaScript

Like other programming languages, a loop in JavaScript allows a set of statements or instructions to be executed repeatedly until a certain condition is fulfilled or true. It is used when some task or operation needs to be performed repeatedly based on some condition. Loops are also called iteration.

Loops in JavaScript

 

Why do we need loops?

Suppose we want to print the message, say “Hello, World” 10 times. You can simply write 10 times, but if you want to print 100 times or if you want to change the message, you will have to change 100 times then it will become very time-consuming and tedious to write and change 100 times. So, to overcome this problem we need to use a loop.

Types of loops in JavaScript

In JavaScript, there are 5 types of loops:

  1. for loop
  2. while loop
  3. do-while loop
  4. for/in loop
  5. forEach loop

For loop

The for loop is also known as an entry-controlled loop because the condition is checked before entering inside the body of the loop.

Syntax

for (initialization; test-expression/condition; increment/decrement)
{
    // statement(s)
}

In Initialization, the loop variable is initialized with some value. The initialization of the variable is done only once when the loop execution starts. From the second iteration, this loop variable is updated.

In test-expression or condition, the value of the loop variable is checked against the condition or test-expression. If the condition evaluates to be true, then the body of the loop is executed, otherwise, iteration stops.

In Increment/Decrement, the loop variable is either incremented or decremented depending upon the requirement. The updated value is again checked against the condition.

flowchart of for loop

// printing numbers from 1 to 10.
for (let i=1;i<=10;i++)
{
    console.log (i);
}

In the above example, the loop variable i is initialized with 1 for the first time. The initialized value of i=1 is checked against the condition and the condition evaluates to be true and the value of i, i.e., 1 is printed, The value of i is incremented by 1, i.e., i=2, and then again the condition is checked. This process continues until the condition fails, i.e., when i>10.

While loop

The while loop is also known as an entry-controlled loop. It is very much similar to for loop but the syntax is different. The execution of the while loop starts by evaluating the condition. If the condition evaluates to be true, then statement (s) or instruction are executed, otherwise, the loop ends.

flowchart of while loop

Syntax

while (condition)
{
    // statement (s)
}

Example

// printing numbers from 10 to 1
let i=10;
while (i>=0)
{
    console.log (i);
    i--;
}

Do-while loop

The do-while loop is exit-controlled because the statement or body of the loop is executed before the condition is checked, i.e. the condition is checked at the end. It will always execute at least once even if the condition is false.

flowchart of do-while loop

Syntax

do {
    // statement (s)
}while (condition);

Example

let i=1;
do{
    console.log (i);
    i++;
} while (i<=10);

For/in a loop

The for/in a loop in JavaScript is used to loop or iterate through the properties of an object.

Syntax

for (key in object) {
    //statement (s)
}

Example

var obj={
    firstname:"Rahul",
    lastname:"Sharma",
    age: 22
}

for (let key in obj)
{
    console.log (key);
}
//Output
//firstname
//lastname
//age
//We can use the property name to print the value.
var obj = {
    firstname:"Rahul",
    lastname:"Sharma",
    age: 22
}

for(let key in obj)
{
    console.log (key+" "+obj[key]);
}

//Output
//firstname Rahul
//lastname Sharma
//age 22

For-Each loop

The forEach loop in JavaScript is used to loop or iterate through the elements of the array.

Syntax

Array.forEach (callback (value,index,array),thisArg) {
    //Operation on each element
}

Callback

It consists of a function to be called for each element of the array.

Value

It is required. It represents the element of an array.

Index

It is optional. It is the index of an element.

array

It is optional. It is an array.

var arr=[1,3,6,2,5];
arr.forEach(function (val) {
    console.log(val);
});

//Output
//1
//3
//6
//2
//5

We can also print the index number along with its value.

var arr=[1,3,6,2,5];
arr.forEach(function (val,index){
    console.log (index+" "+val);
});

//Output
//0 1
//1 3
//2 6
//3 2
//4 5

We can also use the arrow function with forEach loop.

var arr = [1,3,6,2,5];
arr.forEach(val => {
    console.log(val);
});

Printing element along with index using arrow function.

var lang=['PHP','Java','JavaScript','C','C++'];
lang.forEach ((element,index) => {
    console.log (index+' '+element);
});

The important point regarding loops is that we should use the correct condition and proper updation of loop variables in loops otherwise it will result in an infinite loop.

for(let i=0;i<5;i--)
    console.log (i);

The output of the above example will be an infinite loop because instead of using the increment operator I have used the decrement operator and the value of i will always be less than 5 and the loop or iteration never ends. So, be very careful while using loops, otherwise it will cause an infinite loop.

I hope you have liked this module. It might not look so easy for you to understand the loops in the first go. You need proper practice to understand this. Practice as many questions as you can so that you can properly understand them. Stay tuned with us for more modules. Until then keep coding!