forEach vs for/of vs for/in vs for loops of arrays in JavaScript

Demystifying the differences between the popular looping techniques of arrays

Hello readers. 👋' In this article, let's deep dive into the differences between some commonly used looping techniques. With the advent of higher-order functions, JavaScript developers rarely use for loops but it is worth knowing the difference between forEach, for, for/in, and for/of.

Let's take the emoji array as shown below.

const emojiArr = [  '😀',  '👋',  '🤣',  '🏖',  'ğŸŽ'  ];

For

This is the traditional for loop used in programming languages. It iterates over the indices and logs the elements of the array.

for(let i=0; i < emojiArr.length; i++ ){
      console.log(`i value: ${i} | Emoji:`, emojiArr[i]);
}

// Output: 
i value: 0 | Emoji: 😀
i value: 1 | Emoji: 👋 
i value: 2 | Emoji: 🤣
i value: 3 | Emoji: 🏖 
i value: 4 | Emoji: ğŸŽ

It takes three expressions in the loop condition:

  • Initialisation
  • Condition to evaluate before the loop starts
  • Expression to evaluate after the loop ends

For Each

forEach is a method of Array.prototype which loops over the elements of the array. It gives us both indices and values of the array. The arrow function makes the code look cleaner.

emojiArr.forEach((emoji, i) => {
      console.log(`i value: ${i} | Emoji:`, emoji);
});

// Output: 
i value: 0 | Emoji: 😀
i value: 1 | Emoji: 👋 
i value: 2 | Emoji: 🤣
i value: 3 | Emoji: 🏖 
i value: 4 | Emoji: ğŸŽ

For-in

It iterates over the enumerable properties of the Array. Numerical indices of the array are the enumerable properties.

for(let i in emojiArr) {
      console.log(`i value: ${i} | Emoji:`, emojiArr[i]);
}

// Output: 
i value: 0 | Emoji: 😀
i value: 1 | Emoji: 👋 
i value: 2 | Emoji: 🤣
i value: 3 | Emoji: 🏖 
i value: 4 | Emoji: ğŸŽ

Some quirks of the for...in loop:

  • In the case of the for...in loop, the indices are of type string and not a number.
  • Both own and inherited properties are considered enumerable properties.
  • It is unsafe for iterating over arrays.
emojiArr.prop = 'new emoji';

// Output: 
i value: prop | Emoji: new emoji

for...in loop takes prop into account while iterating over the array elements


For-of

for...of iterates over the elements of the array and not the indices. It loops over only on "iterable collections". Objects are not iterable.

for(let i of emojiArr) {
      console.log(`i value: ${i} | Emoji:`, emojiArr[i]);
}

// Output
i value: 😀   | Emoji: undefined
i value: 👋   | Emoji: undefined
i value: 🤣   | Emoji: undefined
i value: 🏖   | Emoji: undefined
i value: ğŸŽ   | Emoji: undefined

Thank you for reading.

I hope this has been helpful. Let me know your feedback in the comments. I would love to connect with you at Twitter | LinkedIn | GitHub

No Comments Yet