JS: Test If Object is Iterable or Iterator 📜

By Xah Lee. Date: . Last updated: .
/*
xah_is_iterator(obj) return true if obj is an iterator

Note: this function is not 100% correct. It needs to test if the next function return value is an IteratorResult object.

Created: 2023-01-16
Version: 2023-01-16
*/

const xah_is_iterator = (
  x,
) => (Reflect.has(x, "next") && (typeof x["next"] === "function"));

/*
xah_is_iterable(obj) return true if obj is iterable.

Note: this function is not 100% correct. It needs to test if Symbol.iterator function return value is an iterator.

Created: 2023-01-16
Version: 2025-05-29
 */

const xah_is_iterable = (
  x,
) => ((Reflect.has(x, Symbol.iterator)) &&
  (typeof (x[Symbol.iterator]) === "function") &&
  xah_is_iterator(x[Symbol.iterator]()));

// HHHH------------------------------
// test

// matchAll return iterator

console.log(xah_is_iterator("number 344".matchAll("3")));
// true

// array is not an iterator object
console.log(xah_is_iterator([3, 4]) === false);
// true

// HHHH------------------------------

console.log(xah_is_iterable([3, 4, 5]));
// true

console.log(xah_is_iterable({ kk: 3, [Symbol.iterator]: 4 }) === false);
// true

JavaScript. Iterable, Iterator