This article was originally published at https://maximorlov.com/forof-vs-forin-memory-trick/
A way to loop through a collection in JavaScript is to use the for...in 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...in 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) {
console.log(language);
}
// 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 for...in 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 Fly*ing **Object. Therefore, I know that for...in* is used to iterate through the keys of an object.
Aliens -> Unidentified Fly*ing **Object* -> for...in object
That's it! 💡
const skills = { javascript: "good", nodejs: "excellent", php: "poor" };
for (const language in skills) {
console.log(language);
}
// Output:
// "javascript"
// "nodejs"
// "php"
Now it works! Yay. 🎉
Note: A more common use case is to iterate through the values of an object, or both the keys and the values. In that case, I prefer to use
Object.entries()
(orObject.values()
for values only) which returns an array of key/value pairs which you can deconstruct in a neat way:const skills = { javascript: "good", nodejs: "excellent", php: "poor" }; for (const [language, level] of Object.entries(skills)) { console.log(`My level of ${language} is ${level}`); }
If for...in 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) {
console.log(fruit);
}
// 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 for...in or for...of.
Whenever you're iterating through a collection in JavaScript, just think about aliens. 👽 🛸
Write clean code. Stay ahead of the curve.
Every other Tuesday, I share tips on how to build robust Node.js applications. Join a community of developers committed to advancing their careers and gain the knowledge & skills you need to succeed.
Top comments (1)
Awesome. A nice, easy to remember mnemonic! Love it!