Protecting Objects

Updated · 7 min read
hardES2026javascriptobjectsfreezedefinepropertydescriptors

JavaScript objects are open by default: anyone holding a reference can add, change or delete properties. Sometimes that's dangerous: shared configuration that one module accidentally changes, constants that must stay constant, objects passed to untrusted code. Object protection gives you three levels of locking (preventExtensions, seal, freeze) and fine control over individual properties through property descriptors and Object.defineProperty.

In One Minute

  • Object.freeze(obj): no adding, removing or changing properties. The strongest level.
  • Object.seal(obj): no adding or removing, but existing properties can still change.
  • Object.preventExtensions(obj): no adding; removing and changing still allowed.
  • All three are shallow: nested objects stay changeable unless you protect them too.
  • Every property has a descriptor (value, writable, enumerable, configurable, or get/set); Object.defineProperty sets it.

The Three Levels

Add propertiesDelete propertiesChange valuesCheck with
Normal objectYesYesYesn/a
Object.preventExtensionsNoYesYesObject.isExtensible
Object.sealNoNoYesObject.isSealed
Object.freezeNoNoNoObject.isFrozen
levels.js▶ Try it
"use strict";
const attempts = (obj) => {
  const results = [];
  for (const [label, action] of [
    ["add", () => { obj.extra = 1; }],
    ["change", () => { obj.currency = "EUR"; }],
    ["delete", () => { delete obj.pageSize; }],
  ]) {
    try {
      action();
      results.push(`${label}: ok`);
    } catch {
      results.push(`${label}: blocked`);
    }
  }
  return results.join(", ");
};
 
console.log("preventExtensions", attempts(Object.preventExtensions({ currency: "USD", pageSize: 25 })));
console.log("seal             ", attempts(Object.seal({ currency: "USD", pageSize: 25 })));
console.log("freeze           ", attempts(Object.freeze({ currency: "USD", pageSize: 25 })));
Output
preventExtensions add: blocked, change: ok, delete: ok
seal              add: blocked, change: ok, delete: blocked
freeze            add: blocked, change: blocked, delete: blocked

In strict mode (modules, classes, or "use strict"), a blocked operation throws a TypeError. In sloppy mode, it silently fails, which is one more reason to use strict mode.

Object.freeze

Object.freeze is the one you'll use most, for configuration and constants:

freeze.js▶ Try it
"use strict";
const LATE_FEES = Object.freeze({ perDay: 2, cap: 30, graceDays: 10 });
 
try {
  LATE_FEES.cap = 1000;
} catch (err) {
  console.log(err.name + ": " + err.message);
}
console.log(LATE_FEES.cap, Object.isFrozen(LATE_FEES));
Output
TypeError: Cannot assign to read only property 'cap' of object '#<Object>'
30 true

Freezing also works on arrays: Object.freeze([9, 10, 11, 12]) blocks push, pop and index assignment. Freezing can't be undone; to "change" a frozen object, create a new one: { ...LATE_FEES, cap: 25 }.

Freezing Is Shallow

shallow.js▶ Try it
const settings = Object.freeze({ currency: "USD", limits: { cap: 30 }, grades: [9, 10] });
 
settings.limits.cap = 1000;
settings.grades.push(11);
console.log(settings.limits.cap, settings.grades);
console.log(Object.isFrozen(settings), Object.isFrozen(settings.limits));
Output
1000 [9, 10, 11]
true false

The outer object is frozen, but the objects it points to aren't. To protect nested data, freeze recursively:

deep-freeze.js▶ Try it
"use strict";
function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (value !== null && typeof value === "object" && !Object.isFrozen(value)) deepFreeze(value);
  }
  return Object.freeze(obj);
}
 
const settings = deepFreeze({ currency: "USD", limits: { cap: 30 }, grades: [9, 10] });
try {
  settings.grades.push(11);
} catch (err) {
  console.log(err.name);
}
console.log(settings.grades, Object.isFrozen(settings.limits));
Output
TypeError
[9, 10] true

The !Object.isFrozen(value) check also stops the function from looping forever on circular references.

Property Descriptors

Every property has hidden attributes, together called its descriptor:

AttributeMeaningDefault for normal assignmentDefault for defineProperty
valueThe property's value(the value)undefined
writableCan the value be changed?truefalse
enumerableDoes it show up in for...in, Object.keys, JSON?truefalse
configurableCan it be deleted, or its attributes changed?truefalse
get / setAccessor functions (instead of value/writable)n/aundefined
descriptors.js▶ Try it
const student = { name: "Navika" };
console.log(Object.getOwnPropertyDescriptor(student, "name"));
 
Object.freeze(student);
console.log(Object.getOwnPropertyDescriptor(student, "name"));
 
console.log(Object.getOwnPropertyDescriptor(Math, "PI"));
Output
{ value: 'Navika', writable: true, enumerable: true, configurable: true }
{ value: 'Navika', writable: false, enumerable: true, configurable: false }
{ value: 3.141592653589793, writable: false, enumerable: false, configurable: false }

Object.freeze simply sets writable and configurable to false on every property (and prevents extensions). Math.PI is built that way.

Object.defineProperty

Object.defineProperty(obj, key, descriptor) creates or changes one property with exact attributes. Note that attributes you leave out default to false:

define.js▶ Try it
const account = { owner: "Advitha" };
 
Object.defineProperty(account, "id", { value: "S-0042", enumerable: true });
Object.defineProperty(account, "internalNote", { value: "VIP", writable: true });
Object.defineProperty(account, "label", {
  get() { return `${this.owner} (${this.id})`; },
  enumerable: false,
});
 
account.id = "changed";
console.log(account.id, account.label);
console.log(Object.keys(account), JSON.stringify(account));
console.log(account.internalNote);
Output
S-0042 Advitha (S-0042)
['owner', 'id'] {"owner":"Advitha","id":"S-0042"}
VIP

Explanation: id is read-only (writable defaults to false), so the assignment silently failed in this non-strict code. internalNote and label are non-enumerable, so they don't appear in Object.keys or JSON, though they can still be read directly. Object.defineProperties(obj, { ... }) defines several at once.

Protection and Prototype Pollution

Freezing shared prototypes is one defense against prototype pollution, an attack where malicious input (often JSON with a "__proto__" key merged carelessly into an object) adds properties to Object.prototype, affecting every object in the program:

pollution.js▶ Try it
function unsafeMerge(target, source) {
  for (const key in source) {
    if (typeof source[key] === "object" && source[key] !== null) {
      target[key] ??= {};
      unsafeMerge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}
 
const attack = JSON.parse('{"__proto__": {"isAdmin": true}}');
unsafeMerge({}, attack);
console.log({}.isAdmin);
delete Object.prototype.isAdmin;
 
function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
    const value = source[key];
    target[key] = value && typeof value === "object" ? safeMerge(target[key] ?? {}, value) : value;
  }
  return target;
}
safeMerge({}, attack);
console.log({}.isAdmin);
Output
true
undefined

Explanation: JSON.parse creates an own property literally named "__proto__". The unsafe merge reads it and assigns into target["__proto__"], which is Object.prototype, so suddenly every object has isAdmin: true. The safe version skips dangerous keys. Other defenses: use Map or Object.create(null) for data from users, validate input against a schema, and in high-security code, Object.freeze(Object.prototype) at startup. The security lessons go deeper.

In Practice

The Fee Tracker's configuration module deep-freezes its settings so no other module can change them by accident, and adds a non-enumerable version that stays out of saved JSON:

config.js▶ Try it
"use strict";
function deepFreeze(obj) {
  for (const v of Object.values(obj)) if (v && typeof v === "object") deepFreeze(v);
  return Object.freeze(obj);
}
 
const config = { currency: "USD", lateFees: { perDay: 2, cap: 30 }, grades: [9, 10, 11, 12] };
Object.defineProperty(config, "version", { value: 3, enumerable: false });
deepFreeze(config);
 
function lateFee(days) {
  return Math.min(Math.max(days - 10, 0) * config.lateFees.perDay, config.lateFees.cap);
}
 
try {
  config.lateFees.cap = 999;
} catch (err) {
  console.log("Blocked:", err.message);
}
console.log(lateFee(40), config.version, JSON.stringify(config));
Output
Blocked: Cannot assign to read only property 'cap' of object '#<Object>'
30 3 {"currency":"USD","lateFees":{"perDay":2,"cap":30},"grades":[9,10,11,12]}

Common Mistakes

Expecting freeze to be deep. It protects one level. Deep-freeze nested data.

Relying on silent failures. In sloppy mode, blocked writes do nothing and report nothing. Use strict mode.

Forgetting defineProperty defaults. Omitted attributes are false: the property becomes read-only and hidden.

Treating non-enumerable as private. It's only hidden from enumeration.

Practice

Challenge: Create a frozen GRADES object mapping grade numbers to names, show that adding a grade fails in strict mode, and create a new object that adds grade 8 without changing the original.

Show solution
grades.js▶ Try it
"use strict";
const GRADES = Object.freeze({ 9: "Freshman", 10: "Sophomore", 11: "Junior", 12: "Senior" });
 
try {
  GRADES[8] = "Eighth";
} catch (err) {
  console.log(err.name);
}
 
const withEighth = Object.freeze({ 8: "Eighth", ...GRADES });
console.log(Object.keys(GRADES).length, Object.keys(withEighth).length, Object.isFrozen(withEighth));
Output
TypeError
4 5 true

Quick check: Protecting objects

3 questions
1Which level still allows changing existing values?
2Is Object.freeze deep?
3What do omitted attributes default to in Object.defineProperty?

Key Takeaways

TaskCode
Make constantObject.freeze(obj)
Is it frozen?Object.isFrozen(obj)
Read a descriptorObject.getOwnPropertyDescriptor(obj, key)
Read-only propertyObject.defineProperty(obj, key, { value, enumerable: true })
Hidden propertyObject.defineProperty(obj, key, { value, enumerable: false })
Change a frozen objectconst updated = { ...obj, key: newValue }

Was this tutorial helpful?

Lesson 100 of 139