JavaScriptStrings

String.prototype.charAt()

Returns the character at the given index. Outside the valid range, it returns an empty string instead of undefined.

Returns
A string with a single character (a UTF-16 unit), or an empty string "" when the index is out of range.
Changes the original
No
On this page

Example

#
JavaScript
const course = 'Python'

console.log(course.charAt(0))
console.log(course.charAt(3))
console.log(course.charAt(10) === '')
console.log(course[10])
Console
P
h
true
undefined

Definition and usage

#

The charAt() method returns a single-character string from the given position, counted from 0. Without an argument, it returns the first character. It's one of the oldest string methods, working even in very old browsers.

It differs from square brackets in how it behaves outside the valid range: text.charAt(100) returns an empty string "", while text[100] returns undefined. Negative indexes are not supported either and also give an empty string, so at() is the tool for counting from the end.

Getting an empty string back can be convenient, since you can immediately call further methods on it, such as charAt(0).toUpperCase(), without risking an error for empty text. The method works on UTF-16 units, so with emoji it returns only half of one.

Syntax

#
Syntax
string.charAt()
string.charAt(index)

Parameters

#
  • index

    number, optional

    The character position, counted from 0. Defaults to 0. A value outside the range gives an empty string.

More examples

#
A safe way to capitalize the first letter
JavaScript
function capitalize(text) {
  return text.charAt(0).toUpperCase() + text.slice(1)
}

console.log(capitalize('exercise'))
console.log(capitalize('').length)
Console
Exercise
0

For an empty string, text[0] would give undefined, and calling undefined.toUpperCase() would throw an error. charAt(0) returns "", so the function always works.

Initials from a first and last name
JavaScript
const fullName = 'Anna Parker'
const initials = fullName
  .split(' ')
  .map((part) => part.charAt(0))
  .join('')

console.log(initials)
Console
AP

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • In new code, text[i] or at(i) are more commonly used for single characters. Choose charAt() when you would rather get "" than undefined outside the valid range.
  • charCodeAt() and codePointAt() return a character's numeric code, for example to check whether it is a digit.

Related entries

#

Spotted a mistake or missing an example? Write to us.