What is the Difference Between ‘for…in’ and ‘for…of’ in JavaScript?

What is the Difference Between ‘for…in’ and ‘for…of’ in JavaScript?

One for enumerables, one for iterables…how should you use each?

Jonathan Hsu
Dec 4, 2019 · 3 min read

Photo by Filip Mroz on Unsplash

Looping has come a long way. Starting with while loops and progressing to vanilla for loops, neither iterate over the actual data structure. Rather, they iterate over a sequence that mirrors the identifiers for user.

let nums = [1,2,3,4,5];for(let i=0; i < nums.length; i++) {
   console.log(nums[i]);
}

The variable i is not actually part of nums, but happens to be analogous to the indexes of nums.

Modern JavaScript has better ways to loop through data — specifically the for...in and for...of loops. Learn the difference between the two as well as the underlying principles that guide us in when to use each.

Enumerables vs Iterables

To understand the distinction between for...in and for...of it is important to define the difference between enumerables and iterables. This can be tricky since there is some overlap and the terms are often used interchangeably.

I like to think of enumerables as a rectangle and iterables as a square. Consequently, all iterables are enumerables; however, not all enumerables are iterables.

Keeping that in mind, let’s dig deeper into their definitions.

We’ll define an enumerable first. The verb enumerate is defined as making mention of — or counting — items one at a time. Applying that to programming, an enumerable becomes an entity where its parts can be distinctly identified and referenced.

Now, on to an iterable. From the root verb iterate, defined as performing in repetition, an iterable is an entity where the same set of actions are performed on each item.

So what’s the difference? Here are some examples of each before we highlight what elevates an enumerable to be an iterable:

  • A bag of M&Ms is an enumerable
  • The line at the DMV is an iterable
  • A pile of books is an enumerable
  • A row of books on a shelf is an iterable
  • JSON objects are enumerables
  • JSON arrays are iterables

Did you figure it the key quality? It’s order. An iterable has an internal order to the pieces whereas an enumerable has distinct parts, but they are unordered.

Using ‘for…in’

We begin with for...in, which is used to loop over an enumerable. This is perfect for counting over key-value pairs in an object, such as the example below.

let person = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "medium-handle": "@jhsu98"
}for(const key in person) {
   console.log(key + ": " + person[key]);
}/*
"first_name: Jonathan"
"last_name: Hsu"
"medium-handle: @jhsu98"
*/

As you can see, the for...in loop will set the temporary variable to each key of the object. Therefore, in this case, what is being counted over are the identifiers.

Using ‘for…of’

OK, now we transition to the for...of loop. This loop has a very similar syntax. However, an iterable is required after the of keyword — in contrast to the requirement of an enumerable with in.

let scores = [43,58,28,69,38];for(const item of scores) {
   console.log(item);
}/*
43
58
28
69
38
*/

If we try to use for...of with an enumerable, expect the following error:

let person = {
   "first_name": "Jonathan",
   "last_name": "Hsu",
   "medium-handle": "@jhsu98"
}for(const item of person) {
   console.log(item);
}/*
"TypeError: person is not iterable
    at gewuhimaza.js:6:84
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
*/

I Thought Arrays Were Enumerables Too

You’re right! We saw that passing an enumerable to for...of will cause an error, but passing an iterable to for...in is accepted.

let scores = [43,58,28,69,38];for(const item in scores) {
   console.log(item);
}/*
"0"
"1"
"2"
"3"
"4"
*/

Similar to how for...in counts over the identifiers of the object, for...in will count over the indexes — think of them as position identifiers.

There you have it. Iterables are a type of enumerable, with the extra quality being an order. Try to be more intentional when describing your data structures and spread the word on the differences between for...in and for...of.

Better Programming

Advice for programmers.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.