charAt Reads Units, charCodeAt Reads Values

Read single UTF-16 code units with charAt and charCodeAt — out-of-range asks return the empty string and NaN instead of throwing, unlike bracket access.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
const text = "Hello";

// charAt 返回字符(超出范围返回空串,不报错)
console.log(text.charAt(0), text.charAt(4), text.charAt(99));

// charCodeAt 返回 UTF-16 码元值(超出范围返回 NaN)
console.log(text.charCodeAt(0), text.charCodeAt(99));

// 索引访问与 charAt 的区别:越界时前者返回 undefined
console.log(text[0], text[99]);

// 增补字符:charAt 返回代理对的一半
const emoji = "👍";
console.log("charAt:", emoji.charAt(0).codePointAt(0).toString(16));
console.log("codePointAt:", emoji.codePointAt(0).toString(16));

// 拼接字符码:fromCharCode 与 fromCodePoint
console.log(String.fromCharCode(72, 105), String.fromCodePoint(0x1f44d));

Output

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

H o 
72 NaN
H undefined
charAt: d83d
codePointAt: 1f44d
Hi 👍

How it works

The file’s state is a handful of top-level bindings: text, emoji.

What to watch for

  • Ready as-is on a bare install of the language.

Applying it

The run emits 2 labeled sections — charAt:, codePointAt: — one per step.

Statements that matter

const text = "Hello";
const emoji = "👍";

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `text`, `emoji`.