A Mnemonic That Finally Makes for…in vs for…of Stick
Source: Dev.to
Intro
There are many articles out there explaining the difference between for...in and for...of. I won’t get into that here.
Instead, this is a simple article that answers a question I keep getting asked…over…and over…and over:
How do I remember when to use for...in vs for...of?
💡 for...in sounds like foreign (as in foreign keys).
- Use
for...into iterate over the keys of an object. - Use
for...ofto iterate over the elements of a collection.
That’s it. Nothing fancy. If you want more info on how this connects back to the official definitions, keep reading.
According to the docs:
-
The
for...instatement iterates over all enumerable string properties of an object.
for…in - JavaScript | MDN -
The
for...ofstatement executes a loop that operates on a sequence of values sourced from an iterable object.
for…of - JavaScript | MDN
Reasoning
Based on the definition of for...in, it is used to iterate over the properties of an object. Object properties are also called keys. In fact, Object.keys() will return the properties of an object.
So I simply think for...in sounds like “foreign”; as in “foreign keys”. If you’re familiar with databases, the term foreign key shouldn’t be foreign to you (pun intended).
Therefore, for...in is for iterating over keys. This means the other one (for...of) must be for iterating over collection elements.
📌 for...in: think “foreign keys”