length Counts UTF-16 Units Not Characters

Measure and index strings by UTF-16 code units: length and bracket access split astral emoji into surrogates, while spread iteration reads whole code points.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
const labels = ["café", "éclair", "🏠", "👍🏽", "a"];

for (const s of labels) {
  console.log(JSON.stringify(s), "units:", s.length, "code points:", [...s].length);
}

console.log("👍".length, [..."👍"].length);

// 索引访问按码元切:增补字符被劈成代理对
console.log("🏠"[0].codePointAt(0).toString(16), "🏠".codePointAt(0).toString(16));

// codePointAt 读取完整码点,即使起点落在低位
const emoji = "👍🏽";
console.log(emoji.codePointAt(0).toString(16), emoji.codePointAt(2).toString(16));

// for...of 按码点迭代,不会被代理对劈开
for (const ch of emoji) console.log(ch, ch.codePointAt(0).toString(16));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

"café" units: 4 code points: 4
"éclair" units: 6 code points: 6
"🏠" units: 2 code points: 1
"👍🏽" units: 4 code points: 2
"a" units: 1 code points: 1
2 1
d83c 1f3e0
1f44d 1f3fd
👍 1f44d
🏽 1f3fd

How it works

The core work runs in nested loops — outer for (const s of labels), inner for (const ch of emoji) console.log(ch, ch.codePointAt(0).toString(16));.

Demo state sits in top-level bindings: labels, emoji.

Watch out for

  • No package installation, no environment variables, no setup steps.

Using it

Output lines are prefixed (👍, 🏠), so the outcome of each step lands visibly on its own printed line.

Key statements

const labels = ["café", "éclair", "🏠", "👍🏽", "a"];
const emoji = "👍🏽";

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `labels`, `emoji`.