Loops in JavaScript

Loops in JavaScript

Hola coders!

In this article, we are going to discuss and learn about loops in JavaScript. It allows you to do a certain task for a certain number of times.

It is an outcome of the DRY (Donot Repeat Yourself) principle.

There are various loops used in JS:

  • for loop
  • while loop
  • do while loop
  • for in loop
  • for of loop

for loop

for loop executes a certain set of code for a certain number of times.

Syntax

for (initialization ; condition ; increment/decrement) {
      //code statements
}

initialization: It is the start of the loop which executes one time

condition: It is a condition check which defines the condition for execution of the code

increment/decrement: It is updating (re-initializing ) the counter which updates after each iteration (each time loop is executed).

Example

//for loop

for (let i = 1 ; i <= 5 ; i = i + 1){
    console.log("Number: ",i)
}

Output

1.PNG

let's understand it,

Here, i=1 is the initialization of the counter. It starts counting the number of times execution of the loop.

i <= 5 is the condition, which checks if the statement is true, then only the code written in the block will get executed.

i = i+1 is the incrementing the counter(i) value by 1, each time loop is executed.

as soon as we hit a condition where the condition becomes false then the loop will not get executed.

refer following snapshot depicting dry run of the loop.

2.PNG

while loop

initialization

while (condition) {
        //while block statements
        re-initialization
}

Similar to for loop , syntax is different

whileloop.jpg

// while loop
let i = 1

while ( i <= 5){
    console.log(i)
    i = i + 1
}

Output

3.PNG

Here, is a slight difference between for loop and while loop. while loop is used when number of iterations are not known.

// program to calculate add digits entered by the user
// num = 546 
// 5 + 4 + 6 = 15

let num = 546 
let rem
let sum = 0
while (num > 0){
    rem = num % 10
    sum = sum + rem
    // re-initialization
    num = Math.floor(num / 10)
}

console.log("Sum of digits: ",sum)

Output

4.PNG

Follow following for more explanation

5.PNG

do while loop

do while loop allows executing the loop even once if the condition is not true.

// do while loop
let i = 6

do {
    console.log("Once it will be executed")
    console.log(i)
    i = i + 1
} while ( i <= 5)

Output

6.PNG

Though, condition is false still, the loop block will get executed once.

for in loop

for in loop executes on the objects (arrays, objects ). It works on the index value in the case of arrays and on leys in the case of objects.

Syntax

for ( let key in element ) {
      // code block
}

Let's start with an example of arrays

// for in loop
let countries = ["Gujrat", "Rajasthan", "Haryana", "Tamil Nadu", "Punjab"]

for (let key in countries){
    console.log(key)
}

It accesses the index number and provides it in output.

7.PNG

To access each element in array

// for in loop
let countries = ["Gujrat", "Rajasthan", "Haryana", "Tamil Nadu", "Punjab"]

for (let key in countries){
    console.log(countries[key])
}

8.PNG

Let's look into an example using objects

let user = {
    name : "John Doe",
    age  : 23,
    course: ['web dev' , 'JS'],
    country : "India"
}

for (let userKey in user){
    console.log(userKey)
}

Output

9.PNG

To access each value in object

let user = {
    name : "John Doe",
    age  : 23,
    course: ['web dev' , 'JS'],
    country : "India"
}

for (let userKey in user){
    console.log(user[userKey])
}

Output

10.PNG

for of loop

for of loop iterates through the values of the iterable. Means, it provides you the direct value of array.

Syntax

for ( let key of element ) {
      // code block
}

Example

// for of loop
let countries = ["Gujrat", "Rajasthan", "Haryana", "Tamil Nadu", "Punjab"]

for (let c of countries){
    console.log(c)
}

Output

11.PNG

NOTE: for of loop cannot be used on objects

12.PNG

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg's blog by becoming a sponsor. Any amount is appreciated!