iterable Object vs Array-like Object in JavaScript

JavaScript

11/22/2022, 12:09:14 PM

by Leo Voon

iterable object

Iterables are objects that implement the Symbol.iterator method.

function isIterable(obj) {
  // checks for null and undefined
  if (obj == null) {
    return false;
  }
  return typeof obj[Symbol.iterator] === 'function';
}

Array-like object

Array-likes are objects that have indexes and length, so they look like arrays. Examples of array-like object are nodeListHTMLCollection

let arrayLike = { // has indexes and length => array-like
  0: "Hello",
  1: "World",
  length: 2
};

// Error (no Symbol.iterator)
for (let item of arrayLike) {}

Convert iterable object / array-like object to Array

iterable obj -> Array

const iterableNodesObj = document.querySelectorAll('p');

// good
const nodes = Array.from(iterableNodesObj);

// best
const nodes = [...iterableNodesObj];

iterable obj -> Array (when map over), because it avoids creating an intermediate array.

let iterable = {from: 1, to: 5, next: ƒ, Symbol(Symbol.iterator): ƒ}

// bad
const plusTwo = [...iterable].map(a => a + 2);

// good
const plusTwo = Array.from(iterable, (a) => a + 2) 

array-like obj -> Array

const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

// good
const arr = Array.from(arrLike);

迷雾散去!💗