Javascript Tutorial – Loops in Javascript

Loops in Javascript

What is Loops

When we want to execute a piece of code for a number of times, without writing it multiple times, then we use loops for that.
For example, If you want to print “Hello World” 5 times, then you can write something like this.

Console.log("Hello World")
Console.log("Hello World")
Console.log("Hello World")
Console.log("Hello World")
Console.log("Hello World")

But this is not an effiecient way to write it, and if the number increases from 5 to 100 or even 1000, then writing it 1000 times doesn’t make sense, and therfore Loops are very useful in these types of Scenarios.

Let’s take 1 more example, where we have to print numbers from 1 to 5, then again we can write something like this.

Console.log(1)
Console.log(2)
Console.log(3)
Console.log(4)
Console.log(5)

Again this is not an effiecient way to write it, and if the number increases from 5 to 100 or even 1000, then writing it 1000 times doesn’t make sense, and therfore Loops are very useful in these types of Scenarios.

Types of Loops

  1. For Loops
  2. While Loops

Types of For Loops

  • for Loop
  • for of Loop – We will discuss later
  • for in Loop – We will discuss later

Types of While Loops

  • while Loop
  • do…..while loop

Implementation of loops

Now, Let’s see,

How can we write the code for printing “Hello World” multiple times using Loops
How can we write the code for printing numbers 1 to 5 using Loops

Using for loop

for(let i=1;i<=5;i++) {
Console.log("Hello World")
}

for(let i=1;i<=5;i++) {
Console.log(i)
}

Using while loop

let i=1;
while(i<5) {
Console.log("Hello World")
i++
}

let i=1;
while(i<5) {
Console.log(i)
i++
}

Using do…..while loop

let i=1;
do {
Console.log("Hello World")
i++
} while(i<5)

let i=1;
do {
Console.log(i)
i++
} while(i<5)

Let’s understand how for loop works

Index of for loop

for(Variable Initialization;Condition;Increament) {
Block of Code
}

Let’s understand how while loop works

Index of while loop

while(Condition) {
Block of Code
}

Let’s understand how do….while loop works

Index of do….while loop

do {
Block of Code
} while(Condition)

Summary

We have covered below topics in this session

  1. What is Loops in Javascript
  2. Types of Loops in Javascript
  3. while loop
  4. do ….. while loop
  5. for loop

Leave a Comment