ยท hands on

Enumberable vs. Iterable in TypeScript: What's the Difference?

In TypeScript, "enumerable" and "iterable" are terms used to describe different aspects of data collections. Enumerable refers to an object's properties that can be counted or iterated over using a `for...in` loop. Iterable, on the other hand, refers to an object that can be traversed through its elements one by one using a `for...of` loop.

In TypeScript, the terms "iterable" and "enumerable" are often used interchangeably when dealing with data collections. However, they do have distinct nuances.

Enumerables

  • Enumerable refers to an object's property that can be counted or iterated over. It is more related to the concept of properties within an object.
  • When an object is said to be enumerable, it means that its properties can be enumerated using a for...in loop.
  • Enumerable properties are usually associated with objects rather than collections like arrays.

Example

const person = { name: 'Benny', age: 36, city: 'Berlin' };
for (let key in person) {
  console.log(key, person[key]);
}

Iterables

  • An iterable is an object that can be iterated over. It means you can traverse through its elements one by one.
  • When an object is said to be iterable, it means that it can be iterated over using a for...of loop.
  • Iterable objects in TypeScript must implement the Symbol.iterator method, which returns an iterator.
  • Examples of iterables include Arrays, Strings, Maps, Sets, etc.

Example

const array: number[] = [1, 2, 3];
for (let item of array) {
  console.log(item);
}

In this example, the array is iterable, and the for...of loop can iterate over its elements.

Back to Blog