Today marks the 3rd week since I started my software engineering bootcamp. One of the first scenarios that I got hung up on was working with arrays and objects and feeling frustrated when trying to access information in those data structures.

Once I fully understood the distinction between what is iterable and what is enumerable I became more confident in working with complex data structures. I wanted to write this blog post to further solidify my understanding of this topic as well as hopefully help another software engineering student someday understand the difference.

To start, what is an official definition of these terms? Merriam-Webster gives these definitions:

iterate: to say or do again or again and again

enumerate: to ascertain the number of or to specify one after another

What I take from these definitions is that iteration isn’t as detailed or specific as enumeration. When we iterate, we are repeating something without concern of what that something really is. When we enumerate we look at each thing and gather information about it. Imagine a toy box full of dog toys. If we open the lid and try and count each toy without touching them, we are iterating. If we pull each toy out and count them we are enumerating. Enumerating also gives us a chance to look at each toy and determine what properties each toy has, such as does it have squeakers?

My dog Olivia and all of her toys! #spoiled

What does this mean for JavaScript? We know that objects are a key:value pair of data and arrays are a collection of data. This data can be strings, numbers, booleans, and we can even have an array of objects! To relate back to our working definition of iterate vs. enumerate I think of Objects as being a more specific data structure than arrays. With an object we have a key:value pair (where we give the key a variable name) that we can reference. Whereas arrays are a more simple data structure that we access through their index.

Technically though…an array is actually an object where the key is the index and the value is what we see in the array. You’ll see this in action further down.

Let’s dig into some example using the JavaScript loops for…in and for…of. These loops allow us to either iterate or enumerate over a collection of data.

The for…in loop is used to enumerate. We can use this on objects and arrays.

The for…of loop is used to iterate. We can only use this on arrays.

Think of our toy box analogy. If I want to inspect each toy I need to go in the toy box. If I just want to see the toys, I open it and check the toys of the box.

#tech #coding #javascript #learning

Learn About The Difference Between Iterate and Enumerate in JavaScript using for Loops
1.20 GEEK