Different for loop in javascript

Loops are one of the most essential features of any programming language which removes the repetition of code. There are different for loop in javascript which can be used in different scenarios. We are going to see how to use each of them effectively.

List of for loop in javascript

  • for loop
  • forEach loop
  • for in loop
  • for of loop

for loop

The basic of all the for loops available in javascript.

Syntax

for(initial condition; test condition; increment / decrement){
   //code to execute
}

For loop are entry controlled loops which means condition is tested before entering the loop body.

for(let i = 0; i < 10; i++){
   console.log(i);
}

//0
//1
//2
.
.
//9

We can use the for loop along with arrays to perform action on its elements.

let arr = [1, 2, 3, 4, 5];
for(let i = 0; i < arr.length; i++){
  console.log(arr[i]);
}
//1
//2
//3
//4
//5

forEach loop

Alternatively we can also use Array.forEach() method to iterate through each array elements.

let arr = [1, 2, 3, 4, 5];
arr.forEach((e, i)=> {
   console.log(`${e} is at index ${i}`);
});

//1 is at index 0
//2 is at index 1
//3 is at index 2
//4 is at index 3
//5 is at index 4

Array.forEach() loops through each element of the array and calls a callback function for each element with element e & its index i.


for of loop

for of iterates over the value of distinct properties of iterable objects like String, Arrays, Map, Set and user defined iterables.

let str = 'prashant';
for(let char of str){
   console.log(char);
}

//p
//r
//a
//s
//h
//a
//n
//t

for in loop

for in statement iterates over the enumerable properties of an object.

let obj = {a: 1, b: 2, c: 3, d: 4};
for(let key in obj){
  console.log(`${key} has value of ${obj[key]}`);
}
//a has value of 1
//b has value of 2
//c has value of 3
//d has value of 4

The order of iteration is implementation-dependent in for in loop which means properties of objects will not be in particular order, so it is better avoid this using on array.

Leave a Reply

Your email address will not be published. Required fields are marked *