Javascript For Loops

Javascript For Loops in the ECMA Standard

Simple For Loop

The simplest type of for loop increments a variable as its iteration method. The variable acts as a counter for every “n”th element within an object.

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

The loop could also be written in a way that explicitly shows what the “n”th object is. Since the previous example increased its variable by 1 each time it looped, n = 1.

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

For-In Loop

The for-in loop always loops over an object’s elements one by oneby array indexes or key-value pairs.

The syntax for the Javascript for-in loop is:


for (let key in object) {
  // code block to be executed
}

If the object is an array, the for-in loop will print out the array indexes in order. If the object contains key-value pairs, the for-in loop will print out each key that exists. The for-in loop does not guarantee that keys within key-value pairs will always be accessed in the same order.

For-Of Loop

The for-of loop is similar to the for-in loop because it loops over an object’s elements one by one. Compared to the for-in loop, it is newer and automatically uses an iterator.

for (let i of object) {
    console.log(object[i]);
}

If the object is an array, the for-of loop will print out the values of the array’s indexes in order. If the object contains key-value pairs, the for-of loop will print out every value that exists.

For-Await-Of Loop

The for-await-of loop is used when you need to iterate over asynchronous objects or functions. It can return values from objects and the results of function calls. You should never use it on synchronous objects or functions.

for await (let i of object) {
    console.log(object[i]);
}
Javascript For Loops
Scroll to top