Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.at()

Reference for JavaScript String.prototype.at(): get the character at an index, including negative indexes from the end, and how it compares with charAt() and brackets.

The at() method of a string returns a new one-character string: the UTF-16 code unit at a given index. It accepts negative integers, which count back from the end, so at(-1) is the last character. If the position does not exist, it returns undefined.

It is the string counterpart of Array.prototype.at() and replaces the common idiom str[str.length - 1].

JavaScript
"hello".at(-1); // "o"

Try it

JS Positions and negative positions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS at() versus charAt() and brackets

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.at(index)
Name Description
index Zero-based position. It is converted to an integer (the fraction is cut off); NaN and a missing argument become 0. A negative value counts back from the end.

Return value: a string of length 1 holding the code unit at that position, or undefined if the position is outside the string.

Exceptions: none.

Usage notes

  • Out of range is undefined, the same as bracket access str[i], but different from charAt(), which returns an empty string.
  • Negative indexes work only with at(). str[-1] is undefined because it looks up a property named "-1".
  • Code units, not characters. Emoji and many rare characters take two code units, so at() can return half of a surrogate pair. Use [...str].at(i) or Array.from(str) to index by code point.
  • Strings are immutable. str.at(0) reads only; you cannot assign through it.
  • Generic and cheap. It is a constant-time lookup, like brackets.
  • Typical uses: last character, character before the last, or a simple check like input.at(-1) === "?".
  • Combine with default values: str.at(-1) ?? "" turns the undefined of an empty string into an empty string.

Browser support

String.prototype.at() is available in current browsers and Node.js. It is newer than charAt(), so check a compatibility table if you must support older environments.