The JavaScript Object.freeze() method
The Object.freeze() method makes an object immutable: you can no longer add, remove or change its properties. const o = Object.freeze({a: 1}) means o.a = 2 is silently ignored (or throws in strict mode). It's a shallow freeze, so nested objects can still be changed.
Overview
Object.freeze() locks an object down. After freezing, attempts to change a property, add a new one or delete one simply don't take effect. It returns the same object, now frozen, and it's the standard way to mark configuration or constants as truly read-only — going further than const, which only stops the variable from being reassigned, not the object's contents from changing.
The behavior of a blocked write depends on the mode. In ordinary (sloppy) code the write fails silently, which can be confusing — your assignment just does nothing. In strict mode (including inside modules and classes), it throws a TypeError, which is usually what you want so mistakes surface loudly.
The big caveat is that the freeze is shallow: only the top level is locked. A nested object or array inside a frozen object can still be mutated. For a fully immutable structure you'd freeze recursively (a "deep freeze"). To check whether an object is frozen, use Object.isFrozen().
Syntax
const frozen = Object.freeze(obj)
const config = Object.freeze({ apiUrl: "/api" });
config.apiUrl = "/other"; // ignored (throws in strict mode)
Parameters
The Object.freeze() method accepts the following parameters.
| Parameter | Description |
|---|---|
obj |
The object to freeze. It is frozen in place and also returned. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const config = Object.freeze({ env: 'prod', debug: false });
config.debug = true; // ignored
config.newKey = 'nope'; // ignored
document.getElementById('out').textContent =
'debug: ' + config.debug + '\n' +
'isFrozen: ' + Object.isFrozen(config);
// debug: false / isFrozen: true
</script>
Best practices
- Use it for true constants and config that must never change at runtime.
- Remember the freeze is shallow — freeze nested objects too (deep freeze) for full immutability.
- Work in strict mode (modules do this automatically) so blocked writes throw instead of failing silently.
- Check with
Object.isFrozen(obj)when you need to know an object's status.
Frequently asked questions
What does Object.freeze() do?
What is the difference between const and Object.freeze()?
const stops the variable being reassigned but lets the object's contents change; Object.freeze() stops the object's contents changing. They solve different problems and are often used together.Why can I still change a nested object after freezing?
Object.freeze() is shallow — only the top level is locked. Freeze nested objects separately for a deep freeze.Why doesn't freezing throw an error when I change a property?
TypeError.