jskatas.org Continuously Learn JavaScript. Your Way.

Iterator: string

The native string is a built-in iterable object

string is iterable

the strings object key Symbol.iterator` is a function
const s = 'abc'; const isA = typeof s.Symbol.iterator; assert.equal(isA, 'function');
use Array.from() to make an array out of any iterable
const s = 'abc'; const arr = s; assert.deepEqual(arr, ['a', 'b', 'c']);

a string`s iterator

has a special string representation
const s = 'abc'; const iterator = s[Symbol.iterator](); const description = iterator.to____(); assert.equal(description, '[object String Iterator]');
iterator.next() returns an object according to the iterator protocol
const s = 'abc'; const iterator = s[Symbol.iterator](); const value = iterator.___(); assert.deepEqual(value, {done: false, value: 'a'});
the after-last call to iterator.next() says done=true, no more elements
const s = 'abc'; const iterator = s[Symbol.iterator](); iterator.next(); assert.equal(iterator.next().done, true);

Required Knowledge

Related Katas

Iterator

Difficulty Level

TBD

First Published

11 May 2015

Stats

5 tests to solve