for...in vs. for...of in JavaScript

for...in and for...of are statements used for iteration. I still get them mixed up (😬), so this is a quick reference post for future me.

for...in

for...in iterates over the enumerable string property names of an object. It includes inherited enumerable properties and excludes property symbols.

const me = Object.create({ firstName: 'Zach', lastName: 'Snoek' });
me.favoriteColor = 'blue';

for (const key in me) {
    console.log(`${key}: ${me[key]}`);
}

/*
"favoriteColor: blue"
"firstName: Zach"
"lastName: Snoek"
*/

for...in and arrays

Arrays are just objects whose property names represent indices. However, an array can have non-index properties, which can lead to some confusing behavior with for...in:

const colors = ['red', 'green', 'blue'];
colors.hello = 'hello';

for (const key in colors) {
    console.log(key);
}

/*
"0"
"1"
"2"
"hello"
*/

Additionally, the index properties are returned as strings, which isn't usually helpful when working with arrays. For these reasons, it's best to use for...of to iterate over arrays.

for...of

for...of iterates over the values returned from an iterable, such as an array, set, or string.

const colors = ['red', 'green', 'blue'];
colors.hello = 'hello';

for (const color of colors) {
    console.log(color);
}

/*
"red"
"green"
"blue"
*/
const string = 'zach';

for (const char of string) {
    console.log(char);
}

/*
"z"
"a"
"c"
"h"
*/

Let's connect

Come connect with me on LinkedIn, Twitter, and GitHub!

If you found this post helpful, please consider supporting my work financially:

☕️Buy me a coffee!

Subscribe for the latest news

Sign up for my mailing list to get the latest blog posts and content from me. Unsubscribe anytime.