Question Bank
JavaScript Immutability and References Quiz
Difficulty: Medium
Lock down objects with `Object.freeze`, build read-only properties with `Object.defineProperty`, and reason about why React leans on immutable updates.
JavaScript Immutability and References Quiz
Lock down objects with `Object.freeze`, build read-only properties with `Object.defineProperty`, and reason about why React leans on immutable updates.
968 views
5
Make obj reject all mutations by freezing it, then predict what happens when client code tries to reassign one of its keys in non-strict mode.
Examples
Example 1:
Input: Object.freeze(obj); obj.name = 'Jane'; console.log(obj.name)
Output: 'John'
Explanation: In non-strict mode the assignment silently fails; in strict mode it throws TypeError. Freeze stops top-level mutation only.Add a non-writable age property valued at 5 to profile so callers can still rename, but cannot change the age. Use Object.defineProperty, not freeze.
Examples
Example 1:
Input: customSeal(profile); profile.name = 'Jane'; profile.age = 10; console.log(profile)
Output: { name: 'Jane', age: 5 }
Explanation: Only the `age` property is non-writable; `name` keeps its default writable descriptor.Rewrite the buggy click handler so it never mutates this.state.words and React's diff still detects the update.
Examples
Example 1:
Input: this.state.words = ['immutable']; this.setState(state => ({ words: [...state.words, 'immutable'] }))
Output: state.words = ['immutable', 'immutable']
Explanation: Returning a new array reference makes React's `Object.is` check fire a re-render and avoids mutation-driven bugs.Two variables, a and b, point at the same object. Use a non-mutating update to give b a different count while leaving a.count unchanged. Then describe one practical advantage of treating data this way.
Examples
Example 1:
Input: const a = { count: 1 }; const b = { ...a, count: 2 }; console.log(a.count, b.count)
Output: 1 2
Explanation: Spread creates a new top-level object so changes to b don't reach a.