Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String length property

Reference for the JavaScript string length property: it counts UTF-16 code units, not characters, so emoji and combining marks give surprising results.

The length property of a string holds the number of UTF-16 code units in it. For plain English text that equals the number of characters, which is why "hello".length is 5. For text with emoji, rare scripts or combining accents, the number can be larger than what a reader would count.

It is a data property on each string value, not a method, so you read it without parentheses. An empty string has length 0.

JavaScript
const length = string.length;

Try it

JS Counting code units

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

No output.

JS Counting what people see

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

No output.

Syntax

JavaScript
string.length
Part Description
Value A non-negative integer: the number of 16-bit code units in the string.
Attributes Not writable, not enumerable, not configurable.

The maximum length of a string depends on the engine; in practice, memory runs out first.

Usage notes

  • It counts code units, not characters. Code points above U+FFFF (most emoji, many historic and rare scripts) are stored as two units called a surrogate pair, so each adds 2.
  • Three levels of "character". Code units are what length counts. Code points are what [...string] and for...of iterate. Graphemes are what a reader perceives as one symbol; use Intl.Segmenter for those.
  • Normalization matters. "รฉ" can be one code point or two. Call normalize() before comparing or counting if the input comes from different sources.
  • Read-only. Assigning to string.length silently does nothing in sloppy mode and throws a TypeError in strict mode (modules and classes are strict). Strings are immutable; build a new string with slice() instead.
  • Do not confuse with arrays. array.length is writable and truncates the array; string.length is not.
  • Cheap to read. Reading length is constant time; you do not need to cache it in loops.
  • Slicing by length can cut a pair in half. "๐Ÿ˜€".slice(0, 1) returns a lone surrogate. Iterate code points or graphemes when you truncate user text.
  • Limits in forms. The maxlength attribute of input also counts UTF-16 code units, so it agrees with string.length.

Browser support

Supported in every browser and JavaScript engine since the first versions of the language.