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.
Question Bank
Easy
JavaScript
6 questions
quiz
references
immutability
js-language
431 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.let a = {};
let b = { key: 'b' };
let c = { key: 'c' };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
console.log(a[c]);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.const obj = {
a: 1,
b: 3,
b: 2,
a: 4,
a: '5',
};
console.log(obj);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.const obj1 = { key: 42 };
const obj2 = obj1;
obj1['anotherKey'] = 20;
obj2.key = 90;
console.log(obj1);
console.log(obj2);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.(function () {
const obj1 = Object.create({ foo: 'bar' });
const obj2 = Object.create({ foo: 'bar' });
console.log(obj1 == obj2);
console.log(obj1 === obj2);
console.log(obj1.toString() == obj2.toString());
console.log(obj1.toString() === obj2.toString());
})();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.const arr1 = [0, 1, 2, 3, 4, 5];
const arr2 = arr1.slice();
arr2[0] = 'x';
console.log(arr1);
console.log(arr2);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.(function () {
var obj1 = { foo: 'foo' };
var obj2 = obj1;
obj2.foo = 'bar';
delete obj1.foo;
console.log(obj1.foo);
console.log(obj2.foo);
})();