Sub topic 3
Length and Accessing Characters
This chapter assumes you know basic JavaScript syntax (variables, functions, loops) and can run code in a browser console or Node.js. It also assumes you have read the earlier chapters on creating strings and on immutability. The at method requires an ES2022 environment: Node.js 16.6+ or any current browser.
A string is an ordered sequence of units, and each unit has a numeric position called an index. Indexes start at 0. This chapter covers how to find out how long a string is, the three ways to read a single character, and how each one behaves when you pass an index that is out of range, negative, or not a whole number.
The length property
length is a property, not a method. It holds the number of UTF-16 code units in the string. For ordinary English text, one code unit is one character.
const s = "hello";
console.log(s.length); // 5
console.log("".length); // 0
console.log("a b".length); // 3 (the space counts)
console.log("\n".length); // 1 (an escape sequence is one unit)Writing s.length() is a common mistake. It throws TypeError: s.length is not a function, because length is a number.
length is also read-only. Strings are immutable, so you cannot shorten one by assigning to its length the way you can with an array:
"use strict";
const s = "hello";
try {
s.length = 2;
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(s.length); // 5In sloppy (non-strict) mode the assignment fails silently instead of throwing. Either way, the string stays the same.
Positive and negative indexes
The first character is at index 0 and the last is at length - 1. The at method also accepts negative indexes, which count back from the end: -1 is the last character and -length is the first.
A negative index i maps to the positive index length + i. For "hello", at(-2) reads index 5 + (-2) = 3, which is "l".
Three ways to read a character
JavaScript gives you bracket notation, charAt, and at. With a valid, non-negative whole-number index, all three return the same one-character string:
const s = "hello";
console.log(s[0], s.charAt(0), s.at(0)); // h h h
console.log(s[4], s.charAt(4), s.at(4)); // o o oThey behave differently at the edges.
const s = "hello";
console.log(s.length); // 5
console.log(s[0], s.at(-1)); // h o
console.log(s.charAt(10)); // "" (empty string)
console.log(s[10]); // undefinedBracket notation
s[i] is a property lookup. The engine converts i to a property key, which is a string, and checks whether the string has an own property with that name. A string has properties named "0", "1", … up to length - 1. Anything else, such as "10", "-1" or "1.5", is not an index property, so the lookup finds nothing and returns undefined.
const s = "hello";
console.log(s[-1]); // undefined (looks for a property named "-1")
console.log(s[1.5]); // undefined (looks for a property named "1.5")
console.log(s["1"]); // e (the key "1" is a valid index)charAt
charAt(i) converts its argument to an integer first. It truncates fractions, and anything that converts to NaN becomes 0. If the result is out of range, including any negative number, it returns the empty string "".
const s = "hello";
console.log(s.charAt(1.9)); // e (1.9 truncates to 1)
console.log(s.charAt()); // h (missing argument becomes 0)
console.log(s.charAt("oops")); // h ("oops" -> NaN -> 0)
console.log(s.charAt(-1)); // "" (negative is out of range)The silent fallback to index 0 can hide bugs. If you pass charAt a variable that is accidentally undefined, you get the first character and no error.
at
at(i) also converts its argument to an integer, so NaN and a missing argument become 0 and fractions truncate toward zero. If the integer is negative, at adds length to it. If the final index is still out of range, it returns undefined.
const s = "hello";
console.log(s.at(-1)); // o
console.log(s.at(-5)); // h
console.log(s.at(-6)); // undefined
console.log(s.at(1.9)); // e
console.log(s.at(-1.9)); // o (-1.9 truncates to -1)
console.log("".at(-1)); // undefinedComparison
| Expression | Valid index | Out of range | Negative index | Fraction (1.9) | `NaN` or missing |
|---|---|---|---|---|---|
| `s[i]` | character | `undefined` | `undefined` | `undefined` | `undefined` |
| `s.charAt(i)` | character | `""` | `""` | truncates | index 0 |
| `s.at(i)` | character | `undefined` | counts from end | truncates | index 0 |
Choosing between them
- To read the last character or a position near the end, use
at(-n).s.at(-1)is shorter thans[s.length - 1]and harder to get wrong. - In a loop with an index you control,
s[i]is the usual choice. It is the shortest form and the one most readers expect. - Use
charAtwhen you want a string back in every case.s.charAt(i).toUpperCase()never throws, whiles[i].toUpperCase()throws aTypeErrorwheniis out of range. - To detect an out-of-range access, compare against
undefinedfroms[i]ors.at(i). Don't test truthiness ofcharAtresults, because the empty string is falsy, and the same check would also go wrong if you later switched methods.
function capitalize(word) {
// charAt(0) returns "" for an empty word, so this is safe
return word.charAt(0).toUpperCase() + word.slice(1);
}
console.log(capitalize("hello")); // Hello
console.log(capitalize("")); // "" (no error)You can read characters but not write them
Strings are immutable, so index properties are read-only. Assigning to one does nothing in sloppy mode and throws in strict mode, and ES modules and classes always run in strict mode.
"use strict";
const s = "hello";
try {
s[0] = "H";
} catch (e) {
console.log(e.constructor.name); // TypeError
}
console.log(s); // helloTo "change" a character, build a new string:
const s = "hello";
const fixed = "H" + s.slice(1);
console.log(fixed); // Hello
function replaceAt(str, index, ch) {
const i = index < 0 ? str.length + index : index;
if (i < 0 || i >= str.length) return str;
return str.slice(0, i) + ch + str.slice(i + 1);
}
console.log(replaceAt("hello", -1, "!")); // hell!Walking through every character
A classic for loop gives you both the index and the character:
const s = "abc";
for (let i = 0; i < s.length; i++) {
console.log(i, s[i]); // 0 a, then 1 b, then 2 c
}Off-by-one errors are the most common bug here. The condition is i < s.length. If you write i <= s.length, the last iteration reads s[3], which is undefined.
When you don't need the index, use for...of. It iterates by code point rather than code unit, which matters for emoji (see the Unicode chapter):
for (const ch of "abc") {
console.log(ch); // a, then b, then c
}Common errors at a glance
| Symptom | Cause | Fix |
|---|---|---|
| `s.length is not a function` | Called `length` like a method | Write `s.length` |
| `undefined` for the last character | Used `s[-1]` or `s[s.length]` | Use `s.at(-1)` or `s[s.length - 1]` |
| `Cannot read properties of undefined` | Called a method on `s[i]` out of range | Check bounds or use `charAt` |
| Assignment `s[0] = "X"` has no effect | Strings are immutable | Build a new string with `slice` |
| Unexpected first character | Passed `undefined` or `NaN` to `charAt` or `at` | Validate the index before the call |
Exercise
Given const s = "world", what do s[s.length], s.charAt(s.length), s.at(-s.length), and s.at(-s.length - 1) evaluate to?
Show answer
s[5] is undefined because there is no property "5". s.charAt(5) is "" because charAt returns the empty string when out of range. s.at(-5) is "w" because -5 + 5 = 0. s.at(-6) is undefined because -6 + 5 = -1 is still out of range.
Exercise
Write a function lastChar(str) that returns the last character of str, or null if str is empty. Use at.
Show answer
function lastChar(str) { const ch = str.at(-1); return ch === undefined ? null : ch; } — lastChar("abc") returns "c" and lastChar("") returns null. Comparing with undefined, rather than testing truthiness, keeps the check correct.
Exercise
Why does "abc".charAt(undefined) return "a" while "abc"[undefined] returns undefined?
Show answer
charAt converts its argument to an integer: undefined becomes NaN, and NaN becomes 0, so it returns the character at index 0. Bracket notation converts undefined to the property key "undefined", and the string has no property with that name, so the lookup returns undefined.