The Difference Between Iterable And Enumerable In JavaScript
JavaScript
07/11/2022
The main difference between iterable and enumerable is that the former applies to values and the latter to properties.
Let's start with an iterable object. When an object is iterable, it means that it has an iterator. An iterator is simply another object that gives you access 🔑 to the values of the object it's attached to. Examples of objects with an iterator are arrays and strings.
const animals = ["cat", "bear", "mouse"]
/* Iterate an array */for (const animal of animals) { console.log(animal) // cat // bear // mouse}
/* Iterate a string */for (const letter of "cat") { console.log(letter) // c // a // t}
Using a for...of
loop, we can iterate all the values of the animals
array and the string cat
.
On the other hand, 👀 when we talk about enumerability, we talk about going over the properties of an object. Take again the first example from before and let's apply a for...in
loop instead.
const animals = ["cat", "bear", "mouse"]
/* Enumerate over an array */for (const animal in animals) { console.log(animal) // 0 // 1 // 2}
Instead of getting the values of the array, we get the property, i.e. key, of each value instead. In an array or string, it's simply the index.
If we were to apply this to a regular object with string properties,
const person = { age: 19 name: "Jack", weight: "70kg",}
/* Enumerate over an object */for (const key in person) { console.log(key) // age // name // weight}
we would get back the names of the properties.
- How To Refresh GraphQL Data After Mutation In Apollo Client
- How To Solve NextAuth Error No Secret In Production