Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype[Symbol.iterator]()

Reference for the JavaScript string iterator: how for...of, spread and Array.from walk a string by code point, and where graphemes still split.

A string is iterable. Its Symbol.iterator method returns an iterator that yields the string one code point at a time, each as a short string. This is what makes for...of, spread ([...text]), Array.from(text) and destructuring work on strings.

Unlike indexing with text[i], which gives you UTF-16 code units, the iterator keeps surrogate pairs together, so an emoji comes out as one item instead of two broken halves.

JavaScript
const iterator = string[Symbol.iterator]();

Try it

JS Code points versus code units

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Driving the iterator by hand

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string[Symbol.iterator]()
for (const codePoint of string) { /* ... */ }
[...string]
Part Description
Parameters None.
Return value A string iterator object with a next() method. Each result's value is a string of one code point (one or two code units).
Exceptions None.

Usage notes

  • Where it is used implicitly: for...of, array spread, Array.from(), new Set(string), destructuring (const [first, second] = "hello") and yield*.
  • Pairs stay together. A valid surrogate pair is yielded as one two-unit string. A lone surrogate (a broken half) is yielded by itself.
  • Not grapheme-aware. Combining marks, skin-tone modifiers, flags and ZWJ sequences span several code points, and each is yielded separately. Use Intl.Segmenter to walk what readers see as one symbol.
  • The iterator is itself iterable and single-use: once done is true, create a new one with string[Symbol.iterator]().
  • Counting code points: [...text].length works, but allocates an array. For very long strings, loop with for...of and count.
  • Reverse carefully. text.split("").reverse().join("") breaks emoji because split("") splits by code units. Spread first.
  • Differences from indexing: text[i], charAt() and length use code units; the iterator, codePointAt() (with manual stepping) and String.fromCodePoint() work with code points.

Browser support

Supported in all current browsers; string iteration arrived with ES2015.