Common Bugs with Objects

📌 Common bugs · objects✍️ Written by Tom Reyes📅 Reviewed 2026-04-19⏱ ~7 min read

Reference traps and missing-key gotchas that bite every beginner working with structured data.

Bee mascot
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
#1

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.
#2

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.
#3

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.
#4

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.
#5

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.

T
Tom Reyes
Reviewer · 12 yrs Java/JVM

Tom spent eight years as a backend engineer in fintech (Java + Kotlin) and four as a lead at an enterprise SaaS company. He reviews every Java example on this site and writes the data-structure deep dives. He cares deeply that beginners aren't taught bad habits they'll have to unlearn. More about Tom →