String.prototype.length

Returns the number of UTF-16 code units in a string, not the number of visible characters.

Signature
string.length
  • Added in JavaScript ECMAScript 1

Return value

numberA non-negative integer: the number of UTF-16 code units the string holds.

length is a read-only own data property of every string. It is not a method, so there are no parentheses. It is computed once when the string is created, which makes reading it constant time — safe to call inside a loop condition.

Code units, not characters

JavaScript stores strings as UTF-16. Characters outside the Basic Multilingual Plane — emoji, musical symbols, many CJK extension characters — are stored as a surrogate pair and count as 2. Combining marks count separately too, so "é" renders as one é but reports a length of 2.

Pick your unit deliberately:

  • str.length — code units. Correct for slicing indexes, buffer sizes, and anything that feeds back into slice() or charCodeAt().
  • [...str].length — code points. Correct for "how many symbols".
  • Intl.Segmenter with granularity: "grapheme" — user-perceived characters. Correct for a character counter shown to a person, since it keeps flags and skin-tone sequences whole.

Writing to it

Assignment is silently ignored in sloppy mode and throws TypeError in strict mode, because the property is non-writable and non-configurable. Strings are immutable; there is no way to truncate one by shortening its length.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Bound a classic for loop that walks a string index by index
  • Validate a form field against a maximum character count
  • Detect an empty string with a cheap str.length === 0 check
  • Compare byte-ish cost of user input before storing it in a fixed-width column

Frequently asked questions

Why does my string length say 2 for one emoji?

Because length counts UTF-16 code units, and emoji above U+FFFF are stored as a surrogate pair of two code units. Use [...str].length for code points, or Intl.Segmenter for what the user perceives as one character.

Is String length a method or a property?

It is a property, so write str.length with no parentheses. Calling str.length() throws a TypeError because a number is not a function.

Can I shorten a string by setting its length?

No. Strings are immutable and length is non-writable, so the assignment is ignored in sloppy mode and throws a TypeError in strict mode. Use str.slice(0, n) to get a shorter string.

More examples

length is not writable

Under strict mode the assignment throws instead of failing quietly. The descriptor shows why: length is non-writable and non-configurable, so truncation has to go through slice().

Example · javascript
"use strict";
const s = "abcdef";
try {
  s.length = 3;
} catch (err) {
  console.log(err.constructor.name); // TypeError
}
console.log(s.length); // 6 — strings are immutable
console.log(Object.getOwnPropertyDescriptor(Object(s), "length"));
// { value: 6, writable: false, enumerable: false, configurable: false }

A character counter that respects graphemes

The last row is the interesting one: a thumbs-up with a skin-tone modifier is 4 UTF-16 code units but a single grapheme, so only the Segmenter count matches what the user sees.

Example · javascript
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
const count = (s) => [...seg.segment(s)].length;

const inputs = ["hello", "naïve", "\u{1F44D}\u{1F3FD}"];
for (const s of inputs) {
  console.log(s, s.length, count(s));
}
// hello 5 5
// naïve 5 5
// 👍🏽 4 1

Discussion

  • Be the first to comment on this lesson.