JavaScript: ‘for…in’ and ‘for…of’ - The difference

JavaScript: ‘for…in’ and ‘for…of’ - The difference

What is the Difference Between ‘for…in’ and ‘for…of’ in JavaScript? One for enumerables, one for iterables…how should you use each?

What is the Difference Between ‘for…in’ and ‘for…of’ in JavaScript? One for enumerables, one for iterables…how should you use each?

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.

Thank you for reading !

JavaScript Data Science Technology Development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

50 Data Science Jobs That Opened Just Last Week

Data Science and Analytics market evolves to adapt to the constantly changing economic and business environments. Our latest survey report suggests that as the overall Data Science and Analytics market evolves to adapt to the constantly changing economic and business environments, data scientists and AI practitioners should be aware of the skills and tools that the broader community is working on. A good grip in these skills will further help data science enthusiasts to get the best jobs that various industries in their data science functions are offering.

Applications Of Data Science On 3D Imagery Data

The agenda of the talk included an introduction to 3D data, its applications and case studies, 3D data alignment and more.

Data Science Course in Dallas

Become a data analysis expert using the R programming language in this [data science](https://360digitmg.com/usa/data-science-using-python-and-r-programming-in-dallas "data science") certification training in Dallas, TX. You will master data...

32 Data Sets to Uplift your Skills in Data Science | Data Sets

Need a data set to practice with? Data Science Dojo has created an archive of 32 data sets for you to use to practice and improve your skills as a data scientist.

Data Cleaning in R for Data Science

A data scientist/analyst in the making needs to format and clean data before being able to perform any kind of exploratory data analysis.