Mutability in JavaScript and TypeScript: const vs readonly

Why const did not protect your object
Sooner or later everyone writes this code and gets surprised by it:
const settings = { theme: 'dark' };
function applyDefaults(config) {
config.theme = 'light'; // looks harmless
}
applyDefaults(settings);
console.log(settings.theme); // "light"
settings is a const, yet its content changed, and the function never touched the variable. Add a few more functions that receive the same object and you get the classic bug: a value changes somewhere far from where you are looking, and nothing in the stack trace points at the culprit.
The root cause is not const. It is how JavaScript stores values. Once you see that, let, const, readonly, as const and Object.freeze stop feeling like five overlapping features and start looking like five tools with five different jobs.
This article covers:
- how primitives and objects live in memory, with an interactive stack and heap demo
- what
constactually guarantees (less than you think) - what TypeScript adds with
readonly,Readonly<T>andas const - why none of that exists at runtime, and what
Object.freezedoes about it - whether
as consthas replacedenum
Primitives vs objects: how values live in memory
Primitives are copied
Numbers, booleans, strings, null, undefined, Symbol and BigInt are primitives. You cannot change one in place. You can only produce a new value.
let greeting = 'hello';
greeting[0] = 'H'; // silently ignored (throws a TypeError in strict mode)
console.log(greeting); // "hello"
const upper = greeting.toUpperCase(); // a new string
console.log(greeting); // "hello", unchanged
console.log(upper); // "HELLO"
String methods never modify the original. They return a new string. That is why passing a primitive to a function is always safe: the function gets its own copy, and the caller’s value cannot be affected.
Primitives are also compared by value, so 5 === 5 is always true.
Objects are shared by reference
Objects, arrays, functions, Map and Set are reference types. The variable does not hold the object. It holds a reference to it, and assigning that variable somewhere else copies the reference, not the object.
A common way to picture this is two regions of memory. The stack holds small, short-lived things such as local variables and references. The heap holds the objects those references point to.
Run the demo below one line at a time and watch what happens in each region. Start with Copy a number, then switch to the other two.
Stack: variables
Heap: objects
A mental model, not a memory dump. Real engines store some values differently, but this is enough to predict what mutates what.
Two things are worth taking from it:
let b = acopies a value.const alias = usercopies an address. After the second one there is still only one object.- A spread copy creates a new outer object, but anything nested inside is still shared. This is called a shallow copy, and it is behind a huge share of “I copied it, why did the original change?” bugs.
A fair warning about the model: “primitives on the stack, objects on the heap” is a simplification. Engines such as V8 keep strings on the heap, store captured closure variables on the heap, and optimize heavily.1 The model is still the right one for reasoning about behavior, because the rule that matters is semantic: assignment copies primitives and shares objects.
Objects are compared by reference, not by contents:
const a = { name: 'John' };
const b = { name: 'John' };
console.log(a === b); // false, two different objects
console.log(a === a); // true, same reference
let vs const: what const really guarantees
let and const control the binding, which is whether the variable can be pointed at something else. They say nothing about whether the value behind it can change.2
let count = 0;
count = 1; // fine
const MAX = 100;
MAX = 200; // TypeError: Assignment to constant variable
const config = { debug: false };
config.debug = true; // fine, the object is still mutable
config = {}; // TypeError: Assignment to constant variable
Put in terms of the demo: const locks the cell on the stack, not the box on the heap. For primitives that is the same thing, which is why const feels like real immutability for numbers and strings. For objects it is not.
This check happens at runtime, and it is the only mutation guard that plain JavaScript gives you out of the box.
Methods that mutate (and their safe twins)
Before reaching for types, check the methods you call every day. Several array methods change the array they are called on, and the bug is invisible because const allows it.
const scores = [30, 10, 20];
const sorted = scores.sort((a, b) => a - b);
console.log(scores); // [10, 20, 30], the original changed
console.log(sorted === scores); // true, sort returns the same array
| Mutates the original | Returns a new array |
|---|---|
sort() |
toSorted() |
reverse() |
toReversed() |
splice() |
toSpliced() |
arr[i] = x |
with(i, x) |
push(), pop(), shift(), unshift() |
spread: [...arr, x] |
The to* methods and with() shipped in ES2023 and are available in all current browsers and Node.js 20 and later.3 If you target older runtimes, copy first: [...scores].sort().
This matters most in React and other state libraries. Calling state.items.sort() mutates the previous state in place, so the reference never changes and your component may not re-render.
TypeScript: readonly catches it before you run the code
TypeScript can enforce rules that JavaScript cannot, but only at compile time. The generated JavaScript contains no trace of readonly. Its value is that the compiler flags a violation before the code ever runs.4
Readonly properties
type Config = {
readonly endpoint: string;
readonly timeout: number;
};
const cfg: Config = { endpoint: '/api', timeout: 5000 };
cfg.endpoint = '/v2'; // Error: Cannot assign to 'endpoint' because it is a read-only property
Readonly arrays
A plain string[] exposes push, pop, splice, sort and the rest. Marking it readonly removes the mutating methods from the type.
const tags: readonly string[] = ['typescript', 'web'];
tags.push('new'); // Error: Property 'push' does not exist on type 'readonly string[]'
tags[0] = 'other'; // Error: Index signature in type 'readonly string[]' only permits reading
const newTags = [...tags, 'new']; // a new array, fine
ReadonlyArray<string> means the same thing. Use whichever reads better.
Readonly function parameters
This is where readonly pays off most. It turns the opening bug of this article into a compile error:
type Settings = { theme: 'dark' | 'light' };
function applyDefaults(config: Readonly<Settings>) {
config.theme = 'light'; // Error: Cannot assign to 'theme' because it is a read-only property
}
For utilities and library code, a Readonly parameter tells callers that their object will come back untouched, and the compiler enforces the promise.
Readonly<T> is shallow
The built-in Readonly<T> marks every direct property as readonly. Nested objects are not affected, which is the type-level version of the shallow copy problem from the demo.
type User = { name: string; address: { city: string } };
type FrozenUser = Readonly<User>;
// { readonly name: string; readonly address: { city: string } }
// ^ city is still mutable
For deep immutability you need a recursive type:
type DeepReadonly<T> = {
readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};
TypeScript does not ship this one, but it is short enough to keep in a utility file. Note that this simple version does not special-case functions, Map or Set, so test it against your own data before trusting it.
A hole in readonly you should know about
readonly is a promise about how you use a reference, not a property of the value, and TypeScript lets you break it by accident. A readonly property is assignable to a mutable one:
type Frozen = { readonly count: number };
type Mutable = { count: number };
const frozen: Frozen = { count: 1 };
const sneaky: Mutable = frozen; // no error
sneaky.count = 99;
console.log(frozen.count); // 99
The compiler does not complain because assignability between those two types is allowed by design. That is one more reason readonly is a safety net for honest code, not a security boundary.
TypeScript: const type parameters (5.0+)
When TypeScript infers a generic argument from a literal, it widens the type by default:
function pickFrom<T extends readonly unknown[]>(values: T): T {
return values;
}
const widened = pickFrom(['a', 'b', 'c']);
// string[], the literal values are gone
Adding const to the type parameter makes TypeScript preserve the literals, as if the argument had as const written on it.5
function pickFrom<const T extends readonly unknown[]>(values: T): T {
return values;
}
const kept = pickFrom(['a', 'b', 'c']);
// readonly ["a", "b", "c"]
This is useful for routing tables, registries and config helpers, where the actual string values need to survive into the type system without callers having to remember as const.
TypeScript: as const
By default TypeScript widens object and array literals:
const direction = 'left';
// type: "left", a const primitive keeps its literal type
const options = { direction: 'left' };
// type: { direction: string }, the property is widened
The as const assertion tells TypeScript to infer the narrowest possible type and mark everything readonly:
const COLORS = {
red: '#c8381a',
blue: '#2a5f8f',
gold: '#b8960c',
} as const;
// { readonly red: "#c8381a"; readonly blue: "#2a5f8f"; readonly gold: "#b8960c" }
type ColorKey = keyof typeof COLORS; // "red" | "blue" | "gold"
type ColorValue = (typeof COLORS)[ColorKey]; // "#c8381a" | "#2a5f8f" | "#b8960c"
Arrays become tuples
const METHODS = ['GET', 'POST', 'DELETE'] as const;
// readonly ["GET", "POST", "DELETE"], a tuple, not string[]
type Method = (typeof METHODS)[number]; // "GET" | "POST" | "DELETE"
function request(url: string, method: Method) {
/* ... */
}
request('/api', 'PATCH'); // Error: '"PATCH"' is not assignable to '"GET" | "POST" | "DELETE"'
The list exists once, and both the runtime array and the union type come from it. Add 'PUT' to the array and the type updates itself.
It is deep, unlike Readonly<T>
as const applies readonly recursively, all the way down:
const CONFIG = {
server: {
host: 'localhost',
ports: [3000, 4000],
},
} as const;
CONFIG.server.host = 'prod'; // Error: read-only property
CONFIG.server.ports[0] = 8080; // Error: read-only property
as const vs enum
Many codebases have moved from enum to as const objects. The reasons are practical.
An enum compiles to real JavaScript, an object built by an immediately invoked function:
enum Direction {
Left = 'left',
Right = 'right',
}
// compiles to roughly:
var Direction;
(function (Direction) {
Direction['Left'] = 'left';
Direction['Right'] = 'right';
})(Direction || (Direction = {}));
The as const version compiles to a plain object literal:
const Direction = {
Left: 'left',
Right: 'right',
} as const;
type Direction = (typeof Direction)[keyof typeof Direction];
// "left" | "right"
// compiles to:
const Direction = { Left: 'left', Right: 'right' };
as const is usually the better choice when:
- you want to use plain strings such as
"left"directly, notDirection.Left - you want the union to stay in sync with the object automatically
- you publish a library and want readable, idiomatic JavaScript in the output
- you run with
erasableSyntaxOnlyor in Node.js type stripping, where enums are not supported because they generate code6
enum can still make sense when:
- you need nominal typing, where two enums with identical values must not be assignable to each other (
as constunions are structural and will overlap) - the codebase already uses enums consistently and mixing styles would cost more than it saves
One old argument against enums no longer holds. Before TypeScript 5.0, a numeric enum accepted any number, so Status = 42 compiled. Since 5.0 that is an error for literal values, so do not use it as a reason to switch.7 The remaining reasons are the output size, the runtime code and the tooling constraints above.
Object.freeze: the only runtime guard
readonly and as const do not exist at runtime. The compiled JavaScript has no memory of them, and anything that reaches your object through plain JavaScript or any can still change it. If you need enforcement while the program runs, use Object.freeze.8
'use strict';
const config = Object.freeze({
endpoint: '/api',
timeout: 5000,
});
config.endpoint = '/v2'; // TypeError in strict mode, silently ignored otherwise
config.newProp = 'x'; // same
ES modules and classes are always strict, so in modern code a write to a frozen object throws instead of failing silently.
TypeScript knows about Object.freeze. It returns Readonly<T>, so you get the runtime protection and the compile-time check from one call.
Freezing is shallow too
const state = Object.freeze({
user: { name: 'John' },
});
state.user = {}; // blocked, the property is frozen
state.user.name = 'Grace'; // works, the nested object is not frozen
This is the same picture as the spread demo. The frozen object on the heap is locked, but its user property points at a second object that is not.
To freeze deeply, recurse through the nested values. Modern runtimes also give you structuredClone for deep copies,9 and a library such as Immer lets you write “mutating” code that produces new immutable state under the hood.
as const vs Object.freeze
People often treat these as the same thing because both leave you with something that feels locked. They protect different stages:
as const |
Object.freeze |
|
|---|---|---|
| When it acts | Compile time | Runtime |
| Exists in the JS | No, it is erased | Yes, it is a real function call |
| Stops mutation | Only in code the compiler checks | Always, even from plain JavaScript |
| Depth | Deep | Shallow |
| Changes the type | Narrows to literals, adds readonly |
Adds readonly to the top level |
They work well together for module-level constants:
const CONFIG = Object.freeze({
apiUrl: 'https://api.example.com',
retry: { attempts: 3 },
} as const);
// compile time: deeply readonly, literal types preserved
// runtime: top-level writes are blocked
// CONFIG.retry.attempts = 5 is an error in TypeScript, but would still run in plain JS
as const covers the whole tree in the type system, and Object.freeze backs the top level at runtime. If you need the nested parts locked at runtime too, freeze them as well.
Which tool to pick
| Goal | Tool |
|---|---|
| Stop reassigning a variable | const |
| Stop reassigning a property (compile time) | readonly prop: T |
| Make all properties of a type readonly | Readonly<T> |
| Stop array mutation (compile time) | readonly T[] or ReadonlyArray<T> |
| Keep literal types from an object or array | { ... } as const |
| Keep literal types in generic inference | function f<const T>(...) |
| Stop mutation at runtime | Object.freeze(...) |
| Deeply readonly type | Custom DeepReadonly<T> |
| Replace an enum with plain JS output | as const object plus derived union |
| Change an array without mutating it | toSorted(), toReversed(), with() |
Key takeaways
- Primitives are copied. Objects are shared by reference. Most mutation bugs come from forgetting the second part.
constlocks the variable, not the object it points to.readonlyis a compile-time check that disappears from the output. It is a safety net, and it can be bypassed.Readonly<T>andObject.freezeare both shallow.as constis deep, but only in the type system.as constis mostly about preserving literal types. Thereadonlypart is a bonus.- Use
as constfor fixed lists and lookup tables, and addObject.freezewhen something outside your type system can reach the object.
The practical default: mark things readonly early, accept Readonly<T> in functions that should not modify their input, prefer toSorted() over sort() on shared data, and reach for as const whenever a fixed set of values needs to flow into your types.
Footnotes
-
MDN Web Docs, “Memory management”, which describes how JavaScript allocates memory for values and objects, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Memory_management ↩
-
MDN Web Docs, “const”, which states that the declaration creates an immutable binding, not an immutable value, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const ↩
-
MDN Web Docs, “Array.prototype.toSorted()”, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted ↩
-
TypeScript Handbook, “Object Types: readonly Properties”, https://www.typescriptlang.org/docs/handbook/2/objects.html#readonly-properties ↩
-
TypeScript documentation, “TypeScript 5.0” release notes, covering
consttype parameters, https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html#const-type-parameters ↩ -
TypeScript documentation, “TypeScript 5.8” release notes, which introduce the
--erasableSyntaxOnlyflag, https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-8.html ↩ -
TypeScript documentation, “TypeScript 5.0” release notes, section on the enum overhaul, https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html#enum-overhaul ↩
-
MDN Web Docs, “Object.freeze()”, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze ↩
-
MDN Web Docs, “structuredClone()”, https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone ↩