Search⌘ K
AI Features

Discussion: How Long Is a Pirate Flag?

Understand how JavaScript counts the length of emojis, focusing on the pirate flag emoji composed of multiple code units and the zero-width joiner. Learn to use the Intl.Segmenter API to correctly measure emoji lengths and handle Unicode characters precisely in your code.

Verifying the output

Now, it’s time to execute the code and observe the output.

Javascript (babel-node-es2024)
// Happy Flag Day!
const flag = "🏴‍☠";
console.log(flag.length);

Understanding the output

You might have anticipated that the output would be 1, but this code will actually output:

4

Emoji zero-width joiner (ZWJ)

The length of emojis may not be what you expect. In JavaScript, some characters and emojis are formed by multiple code units, which can lead to unexpected results when using the length property. The pirate flag emoji is called an emoji ZWJ sequence, and it’s made up of two separate emojis:

🏴‍☠ = 🏴 + ☠ ...