Object.freeze()

ES5+

Freezes an object, preventing new properties from being added and existing properties from being removed or changed.

Syntax

Object.freeze(obj)

Parameters

obj Object

The object to freeze

Return Value

Object

The frozen object

Examples

JavaScript
const obj = { name: 'John' };
Object.freeze(obj);
obj.name = 'Jane';
obj.age = 30;
console.log(obj);
Output:
// { name: 'John' }

📌 When to Use

Use Object.freeze() to create immutable configuration objects, constants that should never change, or to enforce immutability in functional programming patterns. It is ideal for protecting critical data structures from accidental modification.

⚠️ Common Mistakes

Expecting Object.freeze() to be deep - it only freezes the top level. Nested objects remain mutable unless you freeze them recursively.

Not knowing that mutations fail silently in non-strict mode - always use "use strict" to get errors when modifying frozen objects.

Using Object.freeze() for security - determined attackers can still work around it. It is for integrity, not security.

✅ Best Practices

Create a deepFreeze utility for truly immutable nested objects: function deepFreeze(obj) { Object.freeze(obj); Object.values(obj).filter(v => typeof v === "object").forEach(deepFreeze); return obj; }

Freeze configuration objects at application startup to catch accidental mutations early during development.

Consider using libraries like Immer for more practical immutability in complex applications.

⚡ Performance Notes

Object.freeze() has minimal runtime overhead - it marks the object internally and is O(n) for n properties. However, frozen objects cannot be optimized by JavaScript engines in the same way as regular objects, which may slightly impact property access speed in some engines. The immutability benefits usually outweigh this minor cost.

🌍 Real World Example

Application Constants and Configuration

Create immutable application configuration that cannot be accidentally modified during runtime.

// Deep freeze utility for nested objects
function deepFreeze(obj) {
  Object.freeze(obj);
  Object.values(obj)
    .filter(value => value && typeof value === 'object')
    .forEach(deepFreeze);
  return obj;
}

// Application configuration - frozen to prevent accidental changes
const APP_CONFIG = deepFreeze({
  api: {
    baseUrl: 'https://api.example.com',
    version: 'v1',
    timeout: 30000
  },
  features: {
    darkMode: true,
    notifications: true,
    analytics: false
  },
  limits: {
    maxFileSize: 10 * 1024 * 1024, // 10MB
    maxRetries: 3
  }
});

// This will silently fail (or throw in strict mode)
APP_CONFIG.api.baseUrl = 'https://hacked.com';
console.log(APP_CONFIG.api.baseUrl);
// Still 'https://api.example.com'

// Check if frozen
console.log(Object.isFrozen(APP_CONFIG)); // true
console.log(Object.isFrozen(APP_CONFIG.api)); // true (because of deepFreeze)

Related Methods