# Iterable and Enumerable

# Iterable and Enumerable

Every property inside every object has a property descriptor called enumerable. This descriptor can be set to either true or false. It means, when you do a for...in loop on that Object you will only see the properties that have enumerable set to true. The other properties are sort of hidden.

Iterable means that the object is similar to a String or an Array. Every character or item inside the object has a specific position. Think about the word hello. If you move any of the letters then it changes the meaning. The h must be in position zero. Arrays and NodeLists are the same. They have a specific order and position for everything inside of them.

Most Objects are NOT iterable. Take this Object as an example:

let obj = {
  a: 4,
  x: true,
  blah: "what"
};
1
2
3
4
5

If we were to change the order of the properties inside the object, it would have NO effect on how the Object works or the values of the properties. So, because the properties do NOT have a specific order, they are not iterable. We can ask the Object to give us the first property or the next property because there is no sequence to follow.

# Iterators

Good news. If you want to make your Object iterable then we can now create a custom iterator for the object. The syntax to do this can be a bit scary but there is a feature called a generator which lets us turn a function into an iterator for our object.

Here is a sample of a generator function with its yield keyword.

function* getSomething() {
  yield myObj.a;
  yield myObj.x;
  yield myObj.blah;
  return;
}

let myObj = {
  a: 4,
  x: true,
  blah: "what"
};

console.log(getSomething()); //output 4
console.log(getSomething()); // output true
console.log(getSomething()); //output "what"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# for...of loops

For all objects that are iterable naturally, or that have a custom iterator, we can use a for...of loop to step through it.

# Practical Custom Iterators

One use case for iterators is in combination with async and fetch. When you are fetching data from really big data sets and you want to grab the data in chunks, then iterators can be used to accomplish this.

Back to Week 10 main page

Last Updated: 11/1/2020, 2:12:38 PM