Skip to content
Do you want a beautiful portfolio of backend projects but dread CSS? Learn more →
A Memory Trick To Remember When to Use for...of vs, Articles by Maxim Orlov

A Memory Trick To Remember When to Use for...of vs

2 min read

A way to loop through a collection in JavaScript is to use the and for...of statements. Depending on whether the collection is an object or an array, you would use either one of these statements.

After 6 years of web development, I still couldn't remember which is which — was for...of for objects and for arrays? 🤔

Then the following happened when I used the wrong loop statement:

const skills = { javascript: "good", nodejs: "excellent", php: "poor" };
for (const language of skills) {

// Uncaught TypeError: skills is not iterable

Every. Single. Time. 😓

To save myself the irritation of reaching out to Google whenever I had to loop through a collection (which is often!), I came up with a mnemonic — a memory trick that helps me remember which loop statement I should use with objects and which one with arrays.

What do and for...of have to do with aliens?

The mnemonic I use that helps me decide which loop statement I need to use for objects vs arrays is to think about aliens.

Aliens?! I hear you say.

Yes, aliens.

Because what do aliens fly in? UFOs! 🛸

UFO stands for Unidentified Flying Object. Therefore, I know that is used to iterate through the keys of an object.

Aliens -> Unidentified Flying Object -> object

That's it! 💡

const skills = { javascript: "good", nodejs: "excellent", php: "poor" };
for (const language in skills) {

// Output:
// "javascript"
// "nodejs"
// "php"

Now it works! Yay. 🎉

If is used for objects, then for...of is used to iterate through the elements of an array.

const fruits = ["mango", "pineapple", "kiwi"];
for (const fruit of fruits) {

// Output:
// "mango"
// "pineapple"
// "kiwi"

This little memory trick has saved me countless Google searches. I hope you'll remember it next time you have to use or for...of.

Whenever you're iterating through a collection in JavaScript, just think about aliens. 👽 🛸

Become a skilled Node.js developer

Every other Tuesday I send an email with tips on building solid Node.js applications. If you want to grow as a web developer and move your career forward with me, drop your email below. 👇

No spam! 🙅🏻‍♀️ Unsubscribe at any time.

You Might Also Like