Sub topic 3
Length and Accessing Characters
This chapter assumes you can declare variables, write a for loop, and run code in Node.js or a browser console. It also builds on the previous two chapters, which covered how to create strings and why they cannot be changed.
Indexes and the length property
A string is an ordered sequence of characters. Each character has a zero-based index, so the first character is at index 0 and the last is at length - 1. The length property is read-only. If you assign to it, JavaScript ignores the assignment.
Three ways to read a character
const s = "hello";
console.log(s.length); // 5
console.log(s[0], s.charAt(0)); // h h
console.log(s[s.length - 1]); // o
console.log(s.at(-1)); // o
// Out of range
console.log(s[10]); // undefined
console.log(s.charAt(10)); // "" (empty string)
console.log(s.at(10)); // undefined
// Negative indexes
console.log(s[-1]); // undefined
console.log(s.charAt(-1)); // ""
console.log(s.at(-5)); // hThe three approaches differ in ways that matter:
| Access | Negative index | Out of range | Non-integer index |
|---|---|---|---|
| `s[i]` | `undefined` | `undefined` | `undefined` (`s[1.7]`) |
| `s.charAt(i)` | `""` | `""` | truncated (`charAt(1.7)` is `"e"`) |
| `s.at(i)` | counts from the end | `undefined` | truncated (`at(1.7)` is `"e"`) |
Brackets look up a property by name, so s[-1] looks for a property called "-1", and no such property exists. at() adds length to a negative argument, which makes s.at(-1) a short way to write s[s.length - 1].
Common errors
Assigning to an index does not change the string. In sloppy mode the assignment fails silently. In strict mode, which includes ES modules and class bodies, it throws an error:
"use strict";
const word = "cat";
try {
word[0] = "b";
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(word); // catThe other common error is an off-by-one in loops. Use < with the length, not <=:
const w = "abc";
for (let i = 0; i < w.length; i++) {
console.log(i, w[i]); // 0 a, 1 b, 2 c
}
for (const ch of w) {
console.log(ch); // a, b, c
}Exercise
Given const id = "ORD-4821", what do id.at(-4), id[-4], id.charAt(20), and id[id.length] each return?
Show answer
id.at(-4) returns "4", because at counts back from the end. id[-4] returns undefined, because there is no property named "-4". id.charAt(20) returns "", because the index is out of range. id[id.length] returns undefined, because the last valid index is length - 1.
Exercise
Write a function lastChar(str) that returns the last character of a string, or an empty string if the input is empty.
Show answer
function lastChar(str) { return str.charAt(str.length - 1); } On an empty string, str.length - 1 is -1, and charAt(-1) returns "". The alternative str.at(-1) ?? "" gives the same result.