Skip to content

Iterables are objects and data structures whose values can be traversed.

Arrays in JavaScript are obviously iterable, as well as strings.

There are other iterable data structures. Among them are Set and Map, and also some objects among what are called Array-like in JavaScript.

An Array-like is an object that resembles an array but is not one, such as the lists returned by certain DOM methods, like document.getElementsByClassName() or document.querySelectorAll() or the arguments object. Array-like objects can be easily transformed into Array with the static method Array.from() (introduced in ES2015).

All these objects (iterables) can be traversed using the for..of loop.

Arrays

Arrays in JavaScript allow you to put an ordered list of values in an object:

javascript
const numbers = [1, 2, 3, 4, 5] // numbers is an Array
typeof numbers // 'object'
numbers instanceof Object // true
Array.isArray(numbers) // true

You can access the value of a particular index of an array with the bracket syntax if and only if the expression inside the brackets evaluates to a positive integer:

javascript
numbers[0] // 1 - index numbering starts at 0
numbers[4] // 5

You can access the length of the array with its length property:

javascript
numbers.length // 5

You can traverse the array in different ways, we will see the for..of loop.

The for-of Loop

The for-of loop is very readable:

javascript
const numbers = [1, 2, 3, 4, 5]
const onlyOddNumbers = []

for (const number of numbers) {
  if (number % 2 === 1) {
    onlyOddNumbers.push(number)
  }
}
onlyOddNumbers // [1, 3, 5]