Sub topic 2
Why Strings Never Change
This chapter assumes you can declare variables with let and const, write functions, and run code in a browser console or Node.js. You should also know that arrays have methods such as push and reverse that change the array they are called on. The previous chapter showed how to create string primitives. This one explains one rule that applies to every string method in the rest of the tutorial: a string value can never be modified after it is created.
What immutability means
A value is immutable when nothing can change its contents after it exists. In JavaScript, every string primitive is immutable. No method, operator, or assignment can turn the value "hello" into "jello". You can only create a new string and point a variable at it.
Two separate things are easy to mix up here:
| Concept | Can it change? | Controlled by |
|---|---|---|
| The string value `"hello"` | Never | The language itself |
| A variable holding a string | Yes, if declared with `let` or `var` | How you declare the variable |
| A `const` variable holding a string | No rebinding | The `const` keyword |
const stops a variable from being reassigned. Immutability is a property of the value. A let variable can hold one string and later hold another, but neither string value is ever altered.
let greeting = "hello";
greeting = "jello"; // the variable now refers to a different string
console.log(greeting); // jello
const fixed = "hello";
// fixed = "jello"; // TypeError: Assignment to constant variable.In the first case nothing happened to "hello". The variable greeting was simply rebound to a different value.
Methods return new strings
Every string method that seems to "change" text gives you back a new string and leaves the original as it was. That covers toUpperCase, trim, replace, padStart, slice, concat, and every other method on String.prototype.
const s = " Hello ";
const upper = s.toUpperCase();
const trimmed = s.trim();
const replaced = s.replace("H", "J");
console.log(JSON.stringify(s)); // " Hello "
console.log(JSON.stringify(upper)); // " HELLO "
console.log(JSON.stringify(trimmed)); // "Hello"
console.log(JSON.stringify(replaced)); // " Jello "JSON.stringify wraps each value in quotes so the spaces are visible. The original s still has its spaces and its capital H after all three calls.
The most common mistake: discarding the result
Because the method returns a new string, calling it without storing the result does nothing useful:
let name = " ada ";
name.trim(); // result thrown away
console.log(`[${name}]`); // [ ada ]
name = name.trim(); // store the result
console.log(`[${name}]`); // [ada]This bug often turns up in loops and in code that cleans up input:
const inputs = [" Alice", "BOB ", " carol "];
// Wrong: forEach discards each trimmed string
inputs.forEach((x) => x.trim().toLowerCase());
console.log(inputs); // [" Alice", "BOB ", " carol "]
// Right: map collects the new strings into a new array
const clean = inputs.map((x) => x.trim().toLowerCase());
console.log(clean); // ["alice", "bob", "carol"]Because each method returns a string, you can chain them: x.trim().toLowerCase() calls toLowerCase on the string that trim returned.
Trying to modify a string directly
You can read a character with bracket notation, as the next chapter covers in detail, so it can seem natural to write one the same way. What happens next depends on whether the code runs in strict mode.
Strict mode is a stricter set of JavaScript rules. You turn it on with a "use strict" directive. It is on automatically inside ES modules and class bodies. Code without it runs in "sloppy mode", which is the default in a browser console and the Node.js REPL.
function sloppy() {
const s = "hello";
s[0] = "j"; // silently ignored
s.length = 0; // silently ignored
s.custom = 42; // silently ignored
console.log(s, s.length, s.custom); // hello 5 undefined
}
function strict() {
"use strict";
const s = "hello";
try {
s[0] = "j";
} catch (e) {
console.log(e.name); // TypeError
}
try {
s.custom = 42;
} catch (e) {
console.log(e.name); // TypeError
}
}
sloppy();
strict();In sloppy mode the failed write gives no warning at all, so the bug only shows up later as wrong output. Strict mode throws a TypeError at the line that tried to write. This is one reason to write code as modules or with "use strict".
Contrast with arrays
Arrays are mutable, and several array methods change the array in place. Strings have no methods like that. This table pairs similar-looking operations:
| Task | Array (mutates) | String (returns new) |
|---|---|---|
| Add to end | `arr.push(x)` | `s + x` or `s.concat(x)` |
| Reverse | `arr.reverse()` | `[...s].reverse().join("")` |
| Change one element | `arr[0] = x` | `x + s.slice(1)` |
| Remove part | `arr.splice(1, 2)` | `s.slice(0, 1) + s.slice(3)` |
To "change" one character, build a new string from pieces of the old one:
const word = "hello";
const changed = "j" + word.slice(1);
console.log(word, changed); // hello jelloTo reverse a string, convert it to an array, use the mutable array method on that array, and join the result back into a string. Spreading with [...s] splits the string by code point. The Unicode chapter explains why that is safer than s.split("") for emoji.
Immutability and functions
Immutability makes string arguments safe to pass around. A function that receives a string cannot change the caller's value, whatever it does internally.
function shoutString(text) {
text = text.toUpperCase(); // rebinds the local parameter only
return text;
}
function shoutArray(list) {
list.push("!"); // mutates the caller's array
return list;
}
const msg = "hi";
const parts = ["hi"];
shoutString(msg);
shoutArray(parts);
console.log(msg); // hi
console.log(parts); // ["hi", "!"]shoutString reassigned its own parameter, and that has no effect outside the function. shoutArray changed the array object that both the caller and the function refer to. With strings, a callee can never change the caller's data, so you never need a defensive copy.
Why the language works this way
Making strings immutable has practical benefits for programmers and for engines.
- Value semantics. Strings compare by content:
"abc" === "ab" + "c"istrue. If strings could change, two equal strings could become unequal later, and comparisons would depend on timing. - Safe keys. Strings are the usual keys for objects and
Map. If a key could change after insertion, the entry would be stored under a key that no longer matches its contents. - Sharing without copying. Engines can let many variables refer to one string in memory, deduplicate identical literals (this is called interning), and represent
sliceresults as views into the parent string. None of this would be safe if a string could change under another reference. - Thread and callback safety. Code in a callback, a promise, or a worker message never sees a string half-modified.
Edge cases to keep in mind
- Methods may return the same value.
"abc".trim()returns a string equal to"abc". Whether the engine reuses the original memory does not matter, because neither value can change. constwith strings is fully frozen. With objects,constonly stops rebinding, and the object's contents can still change. Aconststring cannot be rebound and cannot change, so in practice it is a true constant.Object.freezeis unnecessary. CallingObject.freeze("abc")returns the primitive unchanged. Primitives are already immutable.- String objects are not mutable text either.
new String("abc")creates an object you can attach properties to, but its characters are still read-only.
Exercise
What does this code print, and why? let t = "cat"; t.toUpperCase(); t[0] = "b"; console.log(t);
Show answer
It prints cat. The result of toUpperCase() is discarded because it is never assigned. The assignment t[0] = "b" cannot change a string value: it is ignored in sloppy mode and would throw a TypeError in strict mode.
Exercise
Write a function capitalize(s) that returns s with its first character uppercased, for example capitalize("hello") returns "Hello". Do not try to assign to an index.
Show answer
function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); } It builds a new string from the uppercased first character and the rest of the original. Using charAt(0) instead of s[0] means an empty string returns "" rather than throwing on undefined.toUpperCase().
Exercise
A teammate writes const tags = [" a", "b "]; for (const tag of tags) { tag.trim(); } and expects tags to be trimmed afterward. Explain the bug and give a fix.
Show answer
trim returns a new string, and the loop discards it. Even tag = tag.trim() would not work, because tag is a const loop variable, and rebinding a loop variable would not change the array anyway. Fix it with const trimmed = tags.map((t) => t.trim());, or write back with tags.forEach((t, i) => { tags[i] = t.trim(); });. The second version works because arrays are mutable.