Object Extensibility and Prototypes in JavaScript: preventExtensions, seal, freeze and setPrototypeOf
Lock objects down and inspect their prototypes: Object.preventExtensions, seal and freeze compared, why freeze is shallow and how to deep freeze, frozen arrays and the copying array methods, getPrototypeOf, setPrototypeOf, Object.create(null), __proto__, and when each is the right tool.
kvi5hnuCode Sprout team member6 min readOn this page
Article 101 controlled individual properties. This article works at the level of the whole object. It covers two object-wide settings: whether new properties can be added (extensibility), and which object it inherits from (its prototype). Both appear in interviews ("what's the difference between seal and freeze?") and in real code: freezing configuration and constants, or creating dictionary objects with no prototype.
Three levels of locking

Object.preventExtensions | Object.seal | Object.freeze | |
|---|---|---|---|
| Add properties | no | no | no |
| Delete properties | yes | no | no |
| Change attributes | yes | no | no |
| Change values | yes | yes | no |
| Check with | Object.isExtensible | Object.isSealed | Object.isFrozen |
Each level includes the previous one: seal is preventExtensions plus making every own property non-configurable; freeze is seal plus making every data property non-writable. All three return the object you pass in, and none can be undone.
Like other failed writes (article 101), violations are silently ignored in sloppy mode and throw TypeError in strict mode. The examples below run in strict mode to make the failures visible.
preventExtensions
"use strict";
const draft = { title: "Notes" };
Object.preventExtensions(draft);
try {
draft.tags = ["work"];
} catch (err) {
console.log("add:", err.name);
}
draft.title = "Meeting notes"; // allowed
delete draft.title; // allowed
console.log(draft, Object.isExtensible(draft));
add: TypeError
{} false
seal
"use strict";
const point = Object.seal({ x: 1, y: 2 });
point.x = 10; // values can still change
for (const action of [() => { point.z = 3; }, () => { delete point.x; }]) {
try {
action();
} catch (err) {
console.log(err.name);
}
}
console.log(point, Object.isSealed(point));
console.log(Object.getOwnPropertyDescriptor(point, "x"));
TypeError
TypeError
{ x: 10, y: 2 } true
{ value: 10, writable: true, enumerable: true, configurable: false }
Sealing fixes an object's shape (its set of keys) while keeping values mutable. That suits objects such as a state record whose fields may change but must never be misspelled into new ones.
freeze
"use strict";
const settings = Object.freeze({
theme: "dark",
limits: { upload: 10 },
});
try {
settings.theme = "light";
} catch (err) {
console.log("write:", err.name);
}
settings.limits.upload = 999; // the nested object is NOT frozen
console.log(settings, Object.isFrozen(settings), Object.isFrozen(settings.limits));
write: TypeError
{ theme: 'dark', limits: { upload: 999 } } true false
freeze only affects the object's own properties. Nested objects, arrays, and accessor properties' setters still work, because a getter or setter isn't a value. For full immutability, freeze recursively:
"use strict";
function deepFreeze(value) {
if ((typeof value === "object" && value !== null) || typeof value === "function") {
for (const key of Reflect.ownKeys(value)) deepFreeze(value[key]);
Object.freeze(value);
}
return value;
}
const config = deepFreeze({ db: { host: "localhost", ports: [5432, 5433] } });
try {
config.db.ports.push(5434);
} catch (err) {
console.log("push:", err.name, Object.isFrozen(config.db.ports));
}
push: TypeError true
A production version should also track visited objects (with a WeakSet, article 78) so that circular references don't cause infinite recursion.
Frozen arrays and other notes
- A frozen array rejects
push,pop,sort,reverse,spliceand index assignment (TypeError), but non-mutating methods work fine, including the ES2023 copying methodstoSorted,toReversed,toSplicedandwith(article 61). Object.freeze(map)doesn't stopmap.set(...): a Map's or Set's entries aren't properties, so their methods keep working.- Primitives are already immutable:
Object.isFrozen(42)istrueandObject.isExtensible("s")isfalse. - A class can freeze instances at the end of its constructor (
Object.freeze(this)) to create immutable value objects. Note that subclasses can then no longer add their own fields. - Freezing has no meaningful performance cost in modern engines, but it also isn't a security boundary on its own.
"use strict";
const scores = Object.freeze([70, 95, 82]);
console.log(scores.toSorted((a, b) => b - a), scores.with(0, 75), scores.map((s) => s + 5));
try {
scores.sort();
} catch (err) {
console.log("sort:", err.name);
}
[ 95, 82, 70 ] [ 75, 95, 82 ] [ 75, 100, 87 ]
sort: TypeError
The prototype attribute
Every object has an internal prototype link (article 70), either another object or null. These functions read and change it:
const english = { greet() { return `Hello, ${this.name}`; } };
const spanish = { greet() { return `Hola, ${this.name}`; } };
const user = Object.create(english);
user.name = "Ana";
console.log(Object.getPrototypeOf(user) === english, english.isPrototypeOf(user), user.greet());
Object.setPrototypeOf(user, spanish);
console.log(user.greet());
console.log(Object.getPrototypeOf([]) === Array.prototype, Object.getPrototypeOf(Object.prototype));
true true Hello, Ana
Hola, Ana
true null
Object.getPrototypeOf(obj)is the standard way to read the prototype.Object.create(proto, descriptors?)creates an object with a given prototype, which is the right time to choose it.Object.setPrototypeOf(obj, proto)changes the prototype of an existing object. It works, but avoid it in hot code: engines optimize property access based on an object's shape and prototype, and changing the prototype later deoptimizes every object and function that touches it. It throws aTypeErrorif the object isn't extensible or if the change would create a cycle.proto.isPrototypeOf(obj)checks whetherprotois anywhere inobj's chain;instanceof(article 70) does the same check againstConstructor.prototype.
Objects with no prototype
Object.create(null) creates an object that inherits nothing: no toString, no hasOwnProperty, and, importantly, no way for a key like "__proto__" or "constructor" to collide with inherited properties:
const counts = Object.create(null);
for (const word of ["constructor", "toString", "constructor"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts, "valueOf" in counts, Object.getPrototypeOf(counts));
[Object: null prototype] { constructor: 2, toString: 1 } false null
With a normal {}, counts["constructor"] would initially be the inherited Object function, so the count would be wrong. For dictionaries, a Map (article 77) is usually even better.
proto
__proto__ is a legacy accessor on Object.prototype that reads and writes the prototype. It's standardized only for web compatibility, and doesn't work on objects without Object.prototype in their chain. Prefer Object.getPrototypeOf/setPrototypeOf.
The one form that remains idiomatic is __proto__ inside an object literal, which sets the prototype at creation time (it's special syntax, not a property):
const animal = { speak() { return `${this.name} makes a sound`; } };
const dog = { __proto__: animal, name: "Rex" };
console.log(dog.speak(), Object.hasOwn(dog, "__proto__"));
Rex makes a sound false
Prototype pollution
Because ordinary objects share Object.prototype, code that merges untrusted JSON into objects can be tricked into modifying it. For example, a naive deep merge of {"__proto__": {"isAdmin": true}} gives every object an isAdmin property. This prototype pollution bug is common in real libraries. Defenses:
- Skip the keys
"__proto__","constructor"and"prototype"when merging. - Use
MaporObject.create(null)for key-value data. - Check
Object.hasOwnbefore trusting a property. - Freeze
Object.prototypein locked-down environments (Node has a--frozen-intrinsicsflag for experimenting with this).
Common questions
What's the difference between seal and freeze?
Both prevent adding and deleting properties. seal still allows changing existing values; freeze also makes data properties read-only.
Does const make an object immutable?
No. const only prevents reassigning the variable. The object it refers to can still be changed unless you freeze it.
Can I unfreeze an object?
No. Freezing, sealing and preventing extensions are permanent. Make a copy instead: const editable = { ...frozen } (shallow) or structuredClone(frozen) (deep, and the clone isn't frozen).
Why is Object.setPrototypeOf discouraged?
It's correct but slow: changing an existing object's prototype invalidates engine optimizations. Pick the prototype when creating the object with Object.create, a class, or __proto__ in a literal.
Summary
preventExtensionsblocks new properties;sealalso blocks deleting and reconfiguring;freezealso blocks value changes.- All three are shallow and permanent; violations fail silently in sloppy mode and throw in strict mode.
- Deep-freeze recursively when you need full immutability; frozen arrays still support the copying methods.
- Read prototypes with
Object.getPrototypeOf, set them at creation withObject.createor a literal's__proto__, and avoidsetPrototypeOfin hot paths. Object.create(null)makes a dictionary with no inherited keys; guard merges against prototype pollution.
Practice Questions
What does this print (in sloppy mode)?
const o = Object.seal({ a: 1 });
o.a = 2;
o.b = 3;
delete o.a;
console.log(o);
Answer
{ a: 2 }. A sealed object allows changing existing values, but adding b and deleting a both fail silently.
Why can the user still change CONFIG.api.url, and how do you prevent it?
const CONFIG = Object.freeze({ api: { url: "https://x" } });
Answer
Object.freeze is shallow: CONFIG.api is frozen as a property (it can't be replaced), but the nested object itself isn't frozen. Freeze recursively with a deepFreeze helper, or freeze the inner object as well:
const CONFIG = Object.freeze({ api: Object.freeze({ url: "https://x" }) });
Why does this word counter give a wrong count for the word "constructor", and what are two fixes?
const counts = {};
for (const w of words) counts[w] = (counts[w] || 0) + 1;
Answer
counts["constructor"] initially returns the inherited Object function, which is truthy, so the first count becomes a string concatenation instead of 1. Use a prototype-less object:
const counts = Object.create(null);
Or use a Map:
const counts = new Map();
for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
What happens when you call Object.setPrototypeOf(a, b) when b already inherits from a?
Answer
It throws a TypeError, because the change would create a cycle in the prototype chain.
Previous: JavaScript Property Attributes: Writable, Enumerable, Configurable and Object.defineProperty
Next: Well-Known Symbols in JavaScript: Symbol.toPrimitive, toStringTag, hasInstance, species and More

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.