DEV Community

Mahlon Gumbs
Mahlon Gumbs

Posted on

A Mnemonic That Finally Makes for…in vs for…of Stick

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 simple question I keep getting asked...over...and over...and over.

The question

How do I remember when to use for...in vs for...of?

My answer

💡 for...in sounds like foreign (as in foreign keys).

So use
👉 for...in to iterate over the keys of an object and
👉 for...of to 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.

Official definitions

According to the docs...

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.

To recap

📌 for...in: think "foreign keys"

Did this make for...in vs for...of click for you?
If not, how do you remember which is which?

Let me know in the comments and share this if you've found it helpful.

Top comments (0)