JavaScript for loops and the differences among them

To maintain fluency in any language, whether it’s a spoken language or a computer programming language, you have to continuously learn…

To maintain fluency in any language, whether it’s a spoken language or a computer programming language, you have to continuously learn about, use, and play with it. Today, while reading about JavaScript, I learned about its new for...of statement.

A random image with JavaScript code

At present, there are several JavaScript for loops. In this short article, I'll show you the differences among them, and you'll see how they are written too.

Here are four of the most used JavaScript for loops.

  • The index-based for loop
  • The forEach method
  • The for...in statement
  • The for...of statement

Each of them have a specific set of situations for which they are most appropriately used.

Index-based For Loop

The index-based for loop is one we see in several programming languages.

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

Output

123

However, it appears to have fallen out of favor in the JavaScript community in lieu of more elegant approaches to looping.

The forEach method

forEach is an Array method that accepts a function that specifies the actions to execute for each item of the Array. The forEach method is only available for Arrays.

let arr = [1, 2, 3]arr.forEach(function(item, index) {  console.log(`Item #${index}: ${item}`)})

Output

Item #0: 1Item #1: 2Item #2: 3

The for…in statement

This way of looping is used to loop over the owned properties of an object. An object’s owned properties are those that it possesses for itself, as opposed to those that it’s able to access through inheritance. You can learn more about Object.hasOwnProperty here.

let obj = { name: 'Robert',  age: 29, hasPet: 'yes' }for (const prop in obj) {  if (prop === 'name') {    console.log('Name is', obj['name'])  }
  if (prop === 'hasPet') {    console.log(`Are pets awesome? ${obj['hasPet']}!`)  }}

Output

Name is RobertAre pets awesome? yes!

The for…of statement

The for...of statement is the most versatile for loop. It allows you to loop over any collection that's iterable (e.g. Strings, Arrays, and Sets to name a few).

for (const char of 'hello') {  console.log(char)}

Output

hello

Now that you know the differences among JavaScript’s many for loops, go forth, and confidently loop!

If you learned something new or enjoyed reading this article, please clap it up 👏 and share it so that others will see it. Feel free to leave a comment too!