String Encoding

Under the hood, JavaScript strings are composed of UTF-16 code units. This means that the majority of characters are represented by a 16-bit number (2 bytes). This encoding system allows JavaScript to support far more than the standard 128 ASCII characters, effortlessly accommodating non-English languages and specialized symbols.

Complex Characters

Some characters require more data than a single 16-bit number can provide. For instance, emojis (😀) require more bits to be accurately represented. To handle this, JavaScript uses a pair of 16-bit numbers (known as a surrogate pair, or 2 code units) to represent a single complex character.

This means you are perfectly safe using Unicode characters inside your strings:

const mascot = "🐸";

The Length Quirk

Because the .length property on a string counts UTF-16 code units rather than perceived visual characters, strings containing emojis will return a longer length than you might intuitively expect.

Practical Example

If a user signs up and includes an emoji in their username, standard string length validation might calculate the character count incorrectly.

const name = "boots🐻";

// Because the bear emoji takes 2 code units, the length is 7 (5 for boots + 2 for the bear)
console.log(`UTF-16 unit length: ${name.length}`); // 7

// Modern syntax can be used to count visual characters accurately
console.log(`Visual character length: ${[...name].length}`); // 6

console.log(`Hi ${name}, welcome!`);