[JavaScript] For Loops And The Differences Among Them

in #programming6 years ago (edited)

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. 

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.

  1. The index-based for loop
  2. The forEach method
  3. The for...in statement
  4. 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

1
2
3

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: 1
Item #1: 2
Item #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 Robert
Are 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

h
e
l
l
o

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

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.034
BTC 63914.94
ETH 3312.82
USDT 1.00
SBD 3.92