String.prototype[@@iterator]()

The [@@iterator]() method returns a new iterator object that iterates over the code points of a String value, returning each code point as a String value.

Try it

Syntax

str[Symbol.iterator]

Return value

A new iterator object.

Description

A String is iterable because it implements the @@iterator method. It means strings can be used in for...of loops, be spread in arrays, etc.

Strings are iterated by Unicode codepoints. This means grapheme clusters will be split, but surrogate pairs will be preserved.

// "Backhand Index Pointing Right: Dark Skin Tone"
[..."👉🏿"]; // ['👉', '🏿']
// splits into the basic "Backhand Index Pointing Right" emoji and
// the "Dark skin tone" emoji

// "Family: Man, Boy"
[..."👨‍👦"]; // [ '👨', '‍', '👦' ]
// splits into the "Man" and "Boy" emoji, joined by a ZWJ

Examples

Using [@@iterator]()

const str = 'A\uD835\uDC68';

const strIter = str[Symbol.iterator]();

console.log(strIter.next().value); // "A"
console.log(strIter.next().value); // "\uD835\uDC68"

Using [@@iterator]() with for..of

const str = 'A\uD835\uDC68B\uD835\uDC69C\uD835\uDC6A';

for (const v of str) {
  console.log(v);
}
// "A"
// "\uD835\uDC68"
// "B"
// "\uD835\uDC69"
// "C"
// "\uD835\uDC6A"

Specifications

Specification
ECMAScript Language Specification
# sec-string.prototype-@@iterator

Browser compatibility

BCD tables only load in the browser

See also