Difference between for-in and for-of in Javascript

Posted in Uncategorized

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Here is a way to help remember the difference between for-in and for-of loops in Javascript.

for-in is “introspective”. It gives the keys. Use for-in on objects. Use for-of for iterables (such as arrays).

for-in returns the “keys” of thing (such as the index of a list or props of an object).

Examples of for-in in Javascript

Here are examples of for-in loop over an array and on an object…

Note that “for-in” is probably NOT what you want when applying to an array.

Examples of for-of in Javascript

For arrays and iterables, you want for-of and it return values as expected. …

But for-of will give TypeError when you apply it on objects. To fix the error, switch back to for-in and do this…


Related Posts

Tags

Share This