Code Logo

Immutable Object with freeze()

Published at25 Jul 2026
JavaScript Data Structures Hard 0 views
Like0

Write a JavaScript function that takes an object and returns a frozen version using Object.freeze(). Frozen objects cannot have properties added, removed, or changed. The function should verify that the object is frozen after the operation.

Object.freeze() is a JavaScript method that makes an object immutable. After freezing, you cannot add new properties, delete existing properties, or change the values of existing properties. The operation is shallow — nested objects are not automatically frozen. For deep immutability, each nested object must be frozen recursively.

Freezing is distinct from sealing (Object.seal()) which prevents adding/deleting properties but allows modifying existing ones, and from preventing extension (Object.preventExtensions()) which only prevents new properties. In strict mode, attempts to modify a frozen object throw TypeError; in sloppy mode, they silently fail.

Time complexity is O(n) where n is the number of properties. Space complexity is O(1) as freeze() modifies the object in place. The frozen state is checked with Object.isFrozen() which returns true for frozen objects.

Edge cases include frozen nested objects (only shallow freeze), arrays (can be frozen too, elements become immutable), and attempting to modify a frozen object (silently fails in sloppy mode, throws in strict mode).

Example Input & Output

Example 1
Input
{}
Output
true
Explanation

Empty object frozen

Example 2
Input
{"x":"y"}
Output
true
Explanation

Another frozen object

Example 3
Input
{"nested":{"a":1}}
Output
true
Explanation

Shallow freeze, nested still mutable

Example 4
Input
{"val":42}
Output
true
Explanation

Frozen object check

Example 5
Input
{"a":1}
Output
true
Explanation

Object is frozen

Algorithm Flow

Recommendation Algorithm Flow for Immutable Object with freeze()
Recommendation Algorithm Flow for Immutable Object with freeze()

Solution Approach

function solution(obj) {
  Object.freeze(obj);
  return Object.isFrozen(obj);
}

Best Answers

javascript - Approach 1
function solution(obj) {
  Object.freeze(obj);
  return Object.isFrozen(obj);
}