JavaScript For loops

1 minute read

Iteration in JavaScript

JavaScript have few ways to loop over any type of data that is iterable. This allows to loop over Array, Map and Set, not Object (by default objects are not iterable).

For loop


const digits = [0,1,2,3,4,5,6,7];

for (let i = 0; i < digits.length; i++){
  console.log(digits[i]);
}

pros: It’s loop construct present in most programming languages

cons:

  • It should keep track of the counter and exit condition.
  • Not all data is structured like an array , so for loop isn’t always an option.

The for in loop


const digits = [0,1,2,3,4,5,6,7];

for (const index in digits){
  console.log(digits[index]);
}

pros: improve upon for loop by elimination of the counting logic and exit condition

cons:

  • Still have to deal with index to access the values of the array
  • loops over all enumerable properties so if we add additional properties to the array’s prototype, then those properties will also appear in the loop.

Array.prototype.decimalfy = function(){
  for (let i = 0; i < this.length; i++){
    this[i] = this[i].toFixed(2);
  }
};

const digits = [0,1,2,3,4,5,6,7];

for (const index in digits){
  console.log(digits[index]);
}

prints

0
1
2
3
4
5
6
7
function() {
   for (let i = 0; i < this.length; i++) {
      this[i] = this[i].toFixed(2);
     }
}

forEach loop

forEach is another type of for loop in JavaScript. However forEach() is actually an array method. so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop.