charAt()

ES3+

Returns the character at the specified index in a string.

Syntax

string.charAt(index)

Parameters

index number

The index of the character to return

Return Value

string

The character at the specified index

Examples

JavaScript
const str = 'Hello';
console.log(str.charAt(0));
console.log(str.charAt(4));
Output:
// 'H' 'o'

📌 When to Use

Use charAt() to access individual characters at known positions, for character-by-character processing, or when you need consistent behavior across all JavaScript environments. For modern code, at() with negative index support is often preferred.

⚠️ Common Mistakes

Using bracket notation str[index] instead of charAt() - bracket notation returns undefined for out-of-range indices, while charAt() returns an empty string.

Forgetting that charAt() does not support negative indices - use at() or str[str.length - 1] for accessing from the end.

Not considering that charAt() returns a string, not a character code - use charCodeAt() when you need the numeric value.

✅ Best Practices

Use at() in modern code for cleaner syntax and negative index support: str.at(-1) for the last character.

charAt() is guaranteed to return an empty string for invalid indices, making it safer for optional chaining scenarios.

For iterating through all characters, prefer for...of loop or spread operator [...str] for cleaner code.

⚡ Performance Notes

charAt() and bracket notation have virtually identical performance in modern engines. For character-by-character processing of large strings, consider if you can use split(), map(), or other array methods that might be more optimized for your use case.

🌍 Real World Example

Character Analysis and String Transformation

charAt() is useful for analyzing individual characters, creating initials, capitalizing words, or any operation that requires character-level access.

// Capitalize first letter of each word
function capitalizeWords(str) {
  return str.split(' ').map(word => {
    if (word.length === 0) return word;
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join(' ');
}

console.log(capitalizeWords('hello world')); // 'Hello World'

// Generate initials from full name
function getInitials(fullName) {
  return fullName
    .split(' ')
    .filter(word => word.length > 0)
    .map(word => word.charAt(0).toUpperCase())
    .join('');
}

console.log(getInitials('John Michael Doe')); // 'JMD'

// Mask sensitive data (credit card, etc.)
function maskNumber(number, visibleChars = 4) {
  const str = String(number);
  if (str.length <= visibleChars) return str;

  let masked = '';
  for (let i = 0; i < str.length - visibleChars; i++) {
    masked += str.charAt(i) === ' ' ? ' ' : '*';
  }
  return masked + str.slice(-visibleChars);
}

console.log(maskNumber('1234 5678 9012 3456'));
// '**** **** **** 3456'

Related Methods