Loops - Javascript

For Loop

// For loop
for (let i = 0; i < 5; i++) {
  console.log(i);
}

Output:

0
1
2
3
4

 

Breaking the loop

// Breaking the loop
for (let i = 0; i < 10; i++) {
  console.log(i);
  if (i == 5) {
    break;
  }
}

Output:

0
1
2
3
4
5

 

Continue the loop

// Continue the loop
for (let i = 0; i < 5; i++) {

  if (i == 2) {
    continue;
  }
  console.log(i);
}

Output:

0
1
3
4

As you can see any statement given after continue ststement don't execute whenever the continue condition is met.

 

While loop

// While Loop
let a = 5;
while(a < 10) {
  console.log(a);
  a++;
}

Output:

5
6
7
8
9

do while loop

// do while Loop
let i = 20

do{
  console.log(i);
  i++;
} while(i < 5)

Output:

20

So you can see in above example do-while loop runs at least once even if condition is not met. So this is the basic difference between while loop and do-while loop.

Looping through an array

// Looping through an array
const cart = ["Apple", "Cold Drinks", "Bread", "Milk"];
for (let i = 0; i < cart.length; i++) {
  console.log(cart[i]);
}

Output:

Apple
Cold Drinks
Bread
Milk

Looping through an array using forEach Loop

// Looping through an array using forEach
const cart = ["Apple", "Cold Drinks", "Bread", "Milk"];
cart.forEach(function(cart_item){
  console.log(cart_item);
})

Output:

Apple
Cold Drinks
Bread
Milk

Using index inside forEach loop

// Looping through an array using forEach
const cart = ["Apple", "Cold Drinks", "Bread", "Milk"];
cart.forEach(function(cart_item, index){
  console.log(`${index} : ${cart_item}`);
})

Output:

Using map method

// Using map method
const voters = [
  {id:125, name:"Jack"},
  {id:217, name:"James"},
  {id:131, name:"Ru"}
]

const ids = voters.map(function(vote){
  return vote.id;
})

console.log(ids);

Output:

[125, 217, 131]

 

Using for loop with in operator

// for-in loop
const voter = {
  name:"John Snow",
  city:"DC",
  age:52
}

for (let x in voter) {
  console.log(`${x} : ${voter[x]}`);
}

Output: