Common Bugs with Conditionals
Five if-statement traps that lurk on every beginner's first big bug list.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
= vs ==
js
let admitted = false;
if (admitted = true) {
console.log("come in");
}
// always runs⚠️
Why this happens
Single = assigns true to admitted, then evaluates as truthy.✅
The fix
=== in JS, == in Python/Java. Modern linters catch this immediately.Truthy / falsy surprises
js
function check(x) {
if (x) console.log("truthy");
else console.log("falsy");
}
check("0"); // truthy! (non-empty string)
check(0); // falsy
check("false"); // truthy⚠️
Why this happens
Strings are truthy regardless of content (except empty). Numbers 0 and NaN are falsy.✅
The fix
When checking specifically for non-zero numbers, write if (x !== 0). Don't rely on coercion.Floating-point equality
py
if 0.1 + 0.2 == 0.3:
print("equal")
# never runs!⚠️
Why this happens
Floats can't exactly represent every decimal. 0.1 + 0.2 is actually 0.30000000000000004.✅
The fix
Compare with a tolerance: abs(a - b) < 1e-9.Missing else when you needed one
js
function getRole(user) {
if (user.isAdmin) return "admin";
if (user.isMember) return "member";
// forgot to return for guests
}⚠️
Why this happens
Functions without explicit return for every path return undefined. Callers crash later.✅
The fix
Always include a default return at the bottom. Or use a switch with a default branch.Comparing strings with == in Java
java
String a = new String("hi");
String b = new String("hi");
if (a == b) {
// never runs
}⚠️
Why this happens
== compares object references in Java for non-primitives. Two new strings are different objects even if their contents match.✅
The fix
Use a.equals(b) for string content comparison.💡
Want the full lesson?
Read Conditionals — the complete lesson, or test yourself with the quiz.