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.
969 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.const obj = { name: 'John', age: 30 };
// freeze obj here
obj.name = 'Jane';
console.log(obj);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.let profile = { name: 'John' };
function customSeal(target) {
// your code here
}
customSeal(profile);
profile.name = 'Jane';
profile.age = 10;
console.log(profile);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.// Inside a React class component (before, buggy):
class Foo extends React.Component {
handleClick() {
const words = this.state.words;
words.push('immutable'); // mutates this.state.words in place
this.setState({ words: words }); // same reference, React may skip the update
}
}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.const a = { count: 1 };
// const b = /* your code, immutable update of `a` */;
const b = a; // placeholder, replace with the immutable update
console.log(a.count, b.count);