How to read the values logged from built in iterables in JavaScript?

Viewed 46

I'm digging into Iterables and Iterators in JavaScript and wanted to understand how to read the value returned from Symbol.iterator for the built in iterables

const str = new String()
const arr = new Array()
const map = new Map()
const set = new Set()

console.log(str[Symbol.iterator]()) Returns Object [String Iterator] {}
console.log(arr[Symbol.iterator]()) Returns Object [Array Iterator] {}
console.log(map[Symbol.iterator]()) Returns [Map Entries] {  }
console.log(set[Symbol.iterator]()) Returns [Set Iterator] {  }

Would someone be able to translate the return value in each of the above cases to simple english readable format please? Thanks in advance

1 Answers

The answer is the same for each: you're getting an iterator back, which you can then use to step through the values contained in the string/object.

let str = 'Foobar'; //no need for a "constructed" string - a literal is fine
let it = str[Symbol.iterator]();
it.next().value; //"F"
it.next().value; //"o", etc

Or for the array:

let arr = [5, 7, 9];
let it = arr[Symbol.iterator]();
it.next().value; //5

---- EDIT ----

In answer to your comment, it is an iterator object. There is no explicit difference between an iterator object belonging to a string versus one belonging to a map - there are just iterables (to which all four of your examples belong) and iterators.

Related