Saturday, March 30, 2024

What are different kinds of loops in Javascript?

JavaScript supports different kinds of loops as described below:

  1. for - loops through a block of code a number of times
  2. for/in - loops through the properties of an object
  3. for/of - loops through the values of an iterable object
  4. while - loops through a block of code while a specified condition is true
  5. do/while - also loops through a block of code while a specified condition is true

for loop:

As we know var declaration is globally scoped where as let and const are block  scoped, let us understand the use of var and let in for loop.

var i = 5;

for (var i = 0; i < 10; i++) {

 }

console.log(i);

let j = 5;

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

}

console.log(j);

Output:

10

5

for in loop:

The JavaScript for in statement loops through the properties of an Object:

for in over object:

The for in loop iterates over a employee object

Each iteration returns a key (x)

The key is used to access the value of the key

The value of the key is employee[x]

const employee = {fname:"Farukh", lname:"Haider"};

let text = "";

for (let x in employee) {

  text += employee[x] + " ";

}

console.log(text);

Output:

Farukh Haider

for in over array:

The for in loop iterates over a number array

Each iteration returns a key (x)

The key is used to access the value of the key

The value of the key is numbers[x]

const numbers = [1, 10, 11, 20];

var sum = 0;

for (let x in numbers) {

  sum += numbers[x] ;

}

console.log(sum);

Output:

42

for of loop:

For/of is not supported in Internet Explorer.

let name = "Farukh";

let text = "";

for (let x of name) {

text += x;

}

console.log(text);

Output:

Farukh

JavaScript While Loop:

The while loop loops through a block of code as long as a specified condition is true.

var i=0;

var text="";

while (i < 2) {

  text += "The number is " + i + " "  ;

  i++;

}

console.log(text);

Output:

The number is 0 The number is 1

The Do While Loop:

This loop will execute the code block once, before checking if the condition is true, then 

it will repeat the loop as long as the condition is true.

var i=0;

var text="";

do {

  text += "The number is " + i;

  i++;

}

while (i < 0);

console.log(text);

Output:

The number is 0

We can also use for forEach() to iterate over Array and Maps as shown below.

forEach() over Array:

const fruits= new Array("Mango", "Apple", "Orange");

var text="";

fruits.forEach(myFunction);

function myFunction(value) {

  text = text + value + " ";

}

console.log(text);

Output:

Mango Apple Orange


forEach() over Map:

forEach() : Invokes a callback for each key/value pair in a Map

const cities = new Map([

  ["Nagpur", "Nag"],

  ["Mumbai", "Mum"],

  ["Delhi", "Del"]

]);

cities.forEach (function(value, key) {

  let text = "";

  text += key + ' = ' + value 

  console.log(text);

})

Output:

Nagpur = Nag

Mumbai = Mum

No comments:

Post a Comment