Codectionary / Developer documentation / JavaScript

String Basics: length, charAt(), at()

Strings are immutable sequences of characters - every string method returns a new string rather than modifying the original. The length property gives the character count. charAt() returns the character at a given index, while the newer at() method also supports negative indices to count from the end.

Syntax

str.length
str.charAt(index)
str.at(index)

Examples

Length and Character Access

Getting a string's length and accessing individual characters.

const text = "Hello";

console.log(text.length);     // 5
console.log(text.charAt(0));  // "H"
console.log(text[1]);         // "e" - bracket access also works
console.log(text.charAt(10)); // "" - out of range returns empty string

at() with Negative Indices

Using at() to easily access characters from the end of the string.

const text = "JavaScript";

console.log(text.at(0));  // "J"
console.log(text.at(-1)); // "t" - last character
console.log(text.at(-2)); // "p" - second to last

// Compare with charAt(), which has no negative index support
console.log(text.charAt(text.length - 1)); // "t" - more verbose equivalent

Best practices

  • Use at(-1) instead of str[str.length - 1] for cleaner access to the last character
  • Remember strings are immutable - "changing" a character actually means creating an entirely new string
  • Use bracket notation (str[0]) or charAt() interchangeably for simple positive-index access - both work identically for valid indices
  • Check .length before accessing indices in a loop to avoid undefined results from out-of-range access

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation