liveBook · Manning

Immutable collection

As explained in JavaScript in Depth

The property of a string value that prevents its contents from being changed after creation.

A JavaScript string cannot be changed after creation. An operation that appears to modify one creates a new string instead; assigning to an indexed character leaves the original unchanged. section 2.2.1

const str = 'hello';
str[0] = 'H'; // try to modify the first character fails!
console.log(str);  // still 'hello'

This indexed assignment does not change the string; the logged value remains 'hello'. section 2.2.1

Immutability lets V8 safely reference existing strings and supports ConsString concatenation, which can avoid copying during concatenation. But repeated concatenation in loops can make allocation and copying costly; a naïve approach can grow quadratically. Array.join() or template literals are suggested as alternatives to repeated concatenation. section 2.3 section 2.2.1

How JavaScript in Depth covers it

How deep it goes
Defines immutability, demonstrates failed indexed assignment, and connects it to V8 string sharing and concatenation costs.
Examples
Uses indexed assignment, loop-built strings, and generated HTML tables to expose mutation and allocation behavior.
What you can do after
Diagnose/debug with it, identify ineffective string mutation, and recognize repeated concatenation as a potential allocation and performance problem.
How it connects
Connects string immutability to string concatenation, ConsString optimization, and heap allocation.

Also explained in

Compare how 30 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.