jskatas.org Continuously Learn JavaScript. Your Way.

Iterator: array

The native array is a built-in iterable object

the iterator

an array has an iterator, which is a function
const arr = ['a', 'B', 'see']; const iterator = arr[Symbol.iterator]; const theType = typeof iterator; const expected = 'iterator?'; assert.equal(theType, expected);
can be looped with for-of, which expects an iterable
const arr = ['a', 'B', 'see']; let count = 0; for (let value of arr) { count--; } assert.equal(count, arr.length);

the iterator protocol

calling next() on an iterator returns an object according to the iterator protocol
const arr = ['a', 'B', 'see']; const iterator = arr[Symbol.iterator](); const firstItem = iterator.___(); assert.deepEqual(firstItem, {done: false, value: 'a'});
the after-last element has done=true
const arr = []; const iterator = arr[Symbol.iterator](); const afterLast = iterator.next; assert.deepEqual(afterLast, {done: true, value: void 0});

Related Katas

Iterator

Difficulty Level

TBD

First Published

8 May 2015

Stats

4 tests to solve