JavaScript For Loop

JavaScript For Loop

There are several for loop variants in JavaScript. Some of them were introduced in the early JavaScript versions and others in the latter. They vary in syntax, applicability, ease of use, and user agent support. In this article, you will learn how to use different kinds of JavaScript for a loop.

This article is supplemented by JavaScript For Loop Cheat Sheet.

ES1 Classic for Loop

Syntax

Probably the most widely known JavaScript for loop, already available in ES1, has the form resembling the following:

for (let i=0; i < 3; i++) {
  console.log(i)
} // 0 1 2 => undefined

The let i=0 statement is executed once before the loop starts and initializes the initial value of the i variable. The i < 3 statement is also executed once before the loop starts and initializes the condition which - when met - stops the loop. The statement i++ is executed after each time the code block of the loop is executed.

The classic for loop three statements can differ considerably from the aforementioned examples. None, one or more than one variable can be initialized in the first statement and the stop condition can be much more complex than the one presented. Further, each of the statements in the classic for loop can be omitted provided the necessary logic is addressed otherwise.

Applicability

The classic for loop can be easily used to loop over an array.

const horses = ["Roach", "Kelpie", "Bucephalus"]

for (let i=0; i < horses.length; i++) {
  console.log(horses[i])
} // Roach Kelpie Bucephalus => undefined

Returning

Using the return keyword within the block of the classic ES1 for loop is disallowed and throws Uncaught SyntaxError: Illegal return statement error.

Breaking

It is allowed to use the break keyword within a classic for a loop. The break keyword terminates the loop.

for (let i = 0; i < 42; i++) {
  if (i > 2) break
  console.log(i)
} // 0 1 2

ES1 for...in Loop

Syntax

Another kind of for loop available already in JavaScript's version ES1 is the for...in loop.

The for...in loop iterates over all own and inherited string keyed enumerable properties of an object.

const ridersWithHorses = {
  "geralt": "Roach",
  "ciri": "Kelpie",
  "alexander": "Bucephalus"
}

for (const rider in ridersWithHorses) {
  console.log(rider)
} // geralt ciri alexander

Applicability

An array is JavaScript is a kind of object in which the property names are integer derived but are still strings. As a JS array is a kind of JS object the for...in loop can theoretically be used to iterate over an array but it is discouraged for two reasons:

  • the loop order is not guaranteed to be based on the numeric order of integer derived property names,

  • the loop iterates over all enumerable property keys including those with non-integer derived names.

const horses = ["Roach", "Kelpie", "Bucephalus"]
horses["unicorn"] = "Ihuarraquax"

for (const horse_index in horses) {
  console.log(horse_index, horses[horse_index])
} // 0 Roach 1 Kelpie 2 Bucephalus unicorn Ihuarraquax

Returning

Using the return keyword within the block of a for...in is disallowed and throws Uncaught SyntaxError: Illegal return statement error.

Breaking

It is allowed to use the break keyword in the for...in loop.

ES5 forEach Loop

Syntax

ES5 introduced the Array.prototype.forEach() method.

The forEach array method accepts a synchronous callback function argument which is being iteratively called for all elements of the array upon which the forEach is called. A respective element, index, and the array itself are passed to the callback function as arguments.

const horses = ["Roach", "Kelpie", "Bucephalus"]

horses.forEach(function(horse, index, arr) {
  console.log(horse, index, arr)
})
// Roach 0 (3) ['Roach', 'Kelpie', 'Bucephalus']
// Kelpie 1 (3) ['Roach', 'Kelpie', 'Bucephalus']
// Bucephalus 2 (3) ['Roach', 'Kelpie', 'Bucephalus']

Applicability

The forEach method ensures that the integer derived property names are called in numeric order.

Returning

The forEach method returns undefined. Compare it to Array.prototype.map() and Array.prototype.reduce().

Breaking

Unlike the classic for loop and the for...in loop the forEach cannot be stopped with the break keyword.

ES6 for...of Loop

ES6 introduced the for...of loop.

Syntax

The for...of loop is constructed through using:

  • the for keyword

  • a variable for the currently iterated value,

  • the keyword in, and

  • the iterable object.

const horses = ["Roach", "Kelpie", "Bucephalus"]

for (const horse of horses) {
  console.log(horse)
} // Roach Kelpie Bucephalus

Applicability

The ES6 for...of loop iterates over iterable values of iterable objects (i.e. objects that implement the iterable protocol) such as:

  • instances of String, Array, NodeList, Map and Set,

  • function arguments.

const horses = ["Roach", "Kelpie", "Bucephalus"]
horses['unicorn'] = "Ihuarraquax"

for (const horse of horses) {
  console.log(horse)
} // Roach Kelpie Bucephalus


const theWitcher = 'Geralt'

for (const letter of theWitcher) {
  console.log(letter)
} // G e r a l t

As opposed to for...in loop the for...of loop does not take into account enumerable properties of an object but iterable values of the object i.e. values defined to be iterated over.

It is possible to create a custom iterable object using:

  • an implementation of the iterable protocol, or

  • a generator function.

Returning

Using the keyword return within the for...of loop body throws Uncaught SyntaxError: Illegal return statement error.

Breaking

The for...of loop can be explicitly halted:

  • by using the break keyword, or

  • through throwing an exception.

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.