Common Bugs with Objects
Reference traps and missing-key gotchas that bite every beginner working with structured data.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
Reading a missing key
py
user = {"name": "Aisha"}
print(user["age"]) # KeyError⚠️
Why this happens
Python raises; JavaScript returns undefined silently (often a worse outcome).✅
The fix
user.get("age", 0) in Python; user.age ?? 0 in JS.Two names, one object
js
const a = { x: 1 };
const b = a;
b.x = 99;
console.log(a.x); // 99⚠️
Why this happens
Variables hold references, not copies, for objects.✅
The fix
const b = {...a} for a shallow copy; structuredClone(a) for deep.Iterating with for-in over an array
js
const xs = [10, 20, 30];
for (const i in xs) {
console.log(xs[i]);
}
// works but i is "0", "1", "2" (strings)⚠️
Why this happens
for-in iterates keys (as strings). for-of iterates values.✅
The fix
Use for-of for arrays. Use for-in for object keys.JSON cycles crash JSON.stringify
js
const obj = { name: "x" };
obj.self = obj;
JSON.stringify(obj); // TypeError: cyclic⚠️
Why this happens
JSON has no concept of references. Cycles cause infinite serialization.✅
The fix
Avoid cycles in serialized data. For state with cycles, serialize a flat representation.Spread doesn't deep-clone
js
const orig = { user: { name: "A" } };
const copy = { ...orig };
copy.user.name = "B";
console.log(orig.user.name); // "B" — shared!⚠️
Why this happens
Spread copies one level. Nested objects still share references.✅
The fix
structuredClone(orig) in modern JS, or hand-roll a deep clone.💡
Want the full lesson?
Read Objects — the complete lesson, or test yourself with the quiz.