Question Bank
JavaScript Object Reference and Key Coercion Traces
Difficulty: Easy
Six traces covering object-key stringification, reference vs literal equality, `Object.create` prototype chains, and shallow-copy aliasing with arrays.
JavaScript Object Reference and Key Coercion Traces
Six traces covering object-key stringification, reference vs literal equality, `Object.create` prototype chains, and shallow-copy aliasing with arrays.
430 views
2
What does the following code print, and why does a[c] overwrite a[b]?
Examples
Example 1:
Input: a[b] = 123; a[c] = 456; log(a[b]); log(a[c]);
Output: 456; 456
Explanation: Plain-object keys are coerced to strings via toString, so both b and c become '[object Object]' and write to the same key.What does the following code print? Which keys actually survive?
Examples
Example 1:
Input: console.log(obj)
Output: { a: '5', b: 2 }
Explanation: Object literals with duplicate keys keep the LAST assignment in source order, silently overwriting earlier ones.What does the following code print, and how does aliasing affect both names?
Examples
Example 1:
Input: log(obj1); log(obj2);
Output: { key: 90, anotherKey: 20 }; { key: 90, anotherKey: 20 }
Explanation: const obj2 = obj1 copies the reference, not the object, so mutations through either name are visible through the other.What does the following code print, and why are the first two comparisons false?
Examples
Example 1:
Input: trace the four comparisons in the IIFE
Output: false; false; true; true
Explanation: obj1 and obj2 are distinct references so == and === return false, but their toString calls both yield '[object Object]' so the string comparisons match.What does each console.log show, and how does slice() differ from a plain alias?
Examples
Example 1:
Input: log(arr1); log(arr2);
Output: [0, 1, 2, 3, 4, 5]; ['x', 1, 2, 3, 4, 5]
Explanation: slice() with no arguments returns a shallow copy of the array, so mutating arr2[0] does not affect arr1.What does this IIFE print, and why does delete obj1.foo make both reads undefined?
Examples
Example 1:
Input: log(obj1.foo); log(obj2.foo);
Output: undefined; undefined
Explanation: obj1 and obj2 alias the same object, so deleting foo through one removes it for both with no prototype-chain fallback.