Common Bugs with Variables
Five real ways beginners get burned by variables — what the bug looks like, why it happens, and the fix.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
Using = when you meant ==
js
if (age = 18) {
console.log("Adult");
}⚠️
Why this happens
You expected to compare age with 18. Instead you assigned 18 to age and the if always runs.✅
The fix
Use === in JS, == in Python and Java.Reassigning a constant
js
const PI = 3.14;
PI = 3.14159; // TypeError⚠️
Why this happens
const locks the variable. Re-running the file with edits is the only way to change it.✅
The fix
If you need to change the value, use let (JS) or just plain assignment (Python). Use const/final only when the value will never change.Reading a variable before declaring it
js
console.log(score); // ReferenceError
let score = 5;⚠️
Why this happens
Before let runs, score doesn't exist in this scope.✅
The fix
Always declare variables at or before first use. Modern editors highlight this immediately.Two variables, one object — the reference trap
js
const a = { x: 1 };
const b = a;
b.x = 99;
console.log(a.x); // 99 — surprised?⚠️
Why this happens
Objects are passed by reference. b = a makes both names point to the same object.✅
The fix
Clone if you want independence: const b = {...a} (shallow) or structuredClone(a) (deep).Shadowing the same name in nested scope
js
let count = 5;
function tick() {
let count = 0; // shadows the outer count
count++;
console.log(count); // 1, not 6
}⚠️
Why this happens
The inner count hides the outer one inside the function.✅
The fix
Use distinct names. If you intend to update the outer one, drop the inner let.💡
Want the full lesson?
Read Variables — the complete lesson, or test yourself with the quiz.