Sub topic 2
Why Strings Never Change
This chapter assumes you know basic JavaScript syntax (variables, let versus const, functions) and can run code in Node.js or a browser console. It also assumes you can create string literals, as covered in the previous chapter.
A JavaScript string is immutable. Once a string value exists, nothing can change its characters. Every string method that seems to modify text actually builds a new string and returns it. The original stays the same.
Trying to Change a Character
Bracket notation lets you read a character, so it looks like it should let you write one too. It does not:
"use strict";
const s = "hello";
try {
s[0] = "j";
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // Cannot assign to read only property '0' of string 'hello'
}
console.log(s); // helloIn strict mode, which ES modules and classes use automatically, the assignment throws a TypeError. In sloppy mode it fails silently. The string is unchanged either way.
Methods Return New Strings
Because strings cannot change, methods like toUpperCase, trim, and replace return a result that you must capture:
const name = " ada ";
name.trim(); // result is thrown away
console.log(`[${name}]`); // [ ada ]
const clean = name.trim();
console.log(`[${clean}]`); // [ada]
console.log(`[${name}]`); // [ ada ] (original unchanged)Calling a method and ignoring its return value is one of the most common string bugs. Arrays behave differently, and that makes the bug easier to fall into: arr.sort() and arr.reverse() modify the array in place. No string method works in place.
Reassignment Is Not Mutation
You can still write code where a variable seems to change:
let greeting = "hi";
greeting = greeting + "!";
greeting += "!";
console.log(greeting); // hi!!Here each + creates a brand-new string, and = points the variable at it. The variable changed. The string values "hi" and "hi!" did not. This is also why const blocks greeting += "!": the code reassigns the variable, and const forbids reassignment.
Why Immutability Helps
Immutability makes strings safe to share:
- No surprises from functions. Passing a string into a function cannot change the caller's copy, because nothing can change it.
- Safe as keys. Strings work reliably as object property names and
Mapkeys because their contents never shift after insertion. - Engine optimizations. Engines can share one copy of identical strings and represent concatenations cheaply, since no one will edit them later.
| Operation | Changes the original? | What happens |
|---|---|---|
| `s[0] = "x"` | No | Ignored, or `TypeError` in strict mode |
| `s.toUpperCase()` | No | Returns a new string |
| `s = s + "x"` | No | Variable now refers to a new string |
| `arr.reverse()` (array) | Yes | Array modified in place |
Exercise
After this code runs, what does the console print, and why? let tag = " Draft "; tag.trim(); tag.toLowerCase(); console.log(tag);
Show answer
It prints " Draft " with its spaces and capital D. trim and toLowerCase each return a new string, and both results are discarded. To keep them, write tag = tag.trim().toLowerCase();.
Exercise
Why does const s = "a"; s += "b"; throw an error even though strings are immutable anyway?
Show answer
s += "b" does not modify the string. It creates the new string "ab" and tries to reassign the variable s to it. const forbids reassignment, so a TypeError is thrown.