JavaScript charAt(): Get a Character by Index

charAt() returns the UTF-16 code unit at a zero-based position in a string as a one-character string. If the index is outside the string, it returns an empty string.

const text = "Hello World";
console.log(text.charAt(4)); // o

charAt() Syntax Top ↑

string.charAt(index)

The first character is index 0. A missing index is treated as 0.

Indexes and Out-of-Range Values Top ↑

This preserves the positions demonstrated on the original page.

const str = "Hello World";
console.log(str.charAt(3));  // l
console.log(str.charAt(4));  // o
console.log(str.charAt(5));  // space
console.log(str.charAt(6));  // W
console.log(str.charAt(20)); // ""
console.log(str.charAt(-2)); // ""

charAt() vs Bracket Access Top ↑

const text = "Welcome";
console.log(text.charAt(3)); // c
console.log(text[3]);       // c

The main difference appears out of range: charAt() returns "", while bracket access returns undefined.

charAt() vs at() for Negative Indexes Top ↑

at() is convenient when you want to count backward from the end with a negative index.

const text = "JavaScript";
console.log(text.at(-1));     // t
console.log(text.charAt(-1)); // ""

Loop Through Characters by Index Top ↑

const word = "ABC";
for (let i = 0; i < word.length; i++) {
  console.log(word.charAt(i));
}

See the for loop tutorial for loop syntax and control flow.

charAt() and Unicode Characters Top ↑

charAt() works in UTF-16 code units. A character outside the Basic Multilingual Plane can use two positions, so charAt() can return only one surrogate half. Use codePointAt() with String.fromCodePoint(), or iterate the string with for...of, when full Unicode code points matter.

const symbol = "😀";
console.log(symbol.length); // 2 UTF-16 code units
console.log([...symbol][0]); // 😀

Character Access in a String-Reverse Exercise Top ↑

Character-by-character access is one way to understand a string reverse algorithm, although spread syntax is safer for many Unicode code points than indexing by UTF-16 unit.

Common charAt() Mistakes Top ↑

  • Starting indexes at 1 instead of 0.
  • Expecting a negative index to count from the end; use at() for that behavior.
  • Expecting an out-of-range call to return undefined; charAt() returns an empty string.
  • Assuming one index always corresponds to one visible Unicode character.

String Reference Lowercase Strings




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer