The string prototype has an @@iterator method.
str[Symbol.iterator]
We can iterate through individual characters.
Manual use of the iterator works as follows:
let message = "abc"; let stringIterator = message[Symbol.iterator](); /*from www.j av a2 s . c om*/ console.log(stringIterator.next()); // {value: "a", done: false} console.log(stringIterator.next()); // {value: "b", done: false} console.log(stringIterator.next()); // {value: "c", done: false} console.log(stringIterator.next()); // {value: undefined, done: true}
When used in a for of loop, the loop will use this iterator to visit each character in order:
for (const c of "abcde") { console.log(c);/*w ww .jav a 2 s . co m*/ }
The string iterator allows for interoperability with the destructuring operator.
This allows you to split a string by its characters:
let message = "abcde"; console.log([...message]); // ["a", "b", "c", "d", "e"]