The Difference Between "for...in" and "for...of" in JavaScript

John John (304)
0

There are two very similar statements in JavaScript: for...in and for...of. And while they can be easily confused, they're actually quite different. In this guide, we'll cover the usage of both statements with multiple examples of each.

In short, for...in iterates over the enumerable properties of an object, while for...of iterates over "iterable collections". There's more nuance, but you can generally think of for...in as iterating over object properties and for...of as iterating over iterable values. Continue reading for further explanation and examples of each.

Posted in these interests:
h/javascript27 guides
h/code69 guides
h/webdev60 guides

The for...in statement iterates over all "non-Symbol, enumerable properties of an object". So what does this mean? Basically, for...in lets you iterate over an object's properties, including properties in the prototype chain.

Why exclude symbols?

Symbols are a primitive data type that are always unique. They are typically used as "private" properties to avoid name clashes when inheritance is intended. And because they're intended for use as "private" properties, for...in will not return them.

What are enumerable properties?

Simply put, enumerable properties are properties that have their enumerable flag set to true, which is the default for most properties. These are properties set either by simple assignment or via a property initializer.

Keep in mind, that for...in also iterates over properties in the prototype chain. See the following example:

const someObj = { someProp: 123 };

let otherObj = Object.create(someObj);
otherObj.otherProp = 456;

for (let key in otherObj) {
  console.log(key);
}

// output

otherProp
someProp

The for...of statement iterates over "iterable objects". Think Array or String, although there are many iterable object types. Object, however, is not iterable by default.

As I mentioned in the intro, think of for...of as iterating over the values of an iterable object.

What is an iterable object?

In order for an object to be iterable, it (or an object in the prototype chain) must implement a @@iterator property, which returns an iterator. An iterator object is an object that includes a next method, which returns the next item in a sequence. There are many built-in iterable objects, like Array and String, for example.

The following example shows the usage of for...of:

const primes = [2, 3, 5, 7];

for (let prime of primes) {
  console.log(prime);
}

// output

2
3
5
7
A comprehensive guide on Python "for" loops
John John (304)
0

Python, like many programming languages, implements containers, which are collections of other objects. As such, Python provides the for statement for iterating over each element in the collection.