Spot the Loose Equality Bug
Find the Mistake Easy
Question
This code logs 'Valid number' even when input is an empty string. What is wrong?
Code
const input = "";
if (input == 0) {
console.log("Valid number");
} else {
console.log("Not a number");
}
Hint
Loose equality coerces types, which can cause unexpected matches.
Explanation
The condition input == 0 uses loose equality. When input is "" (empty string), JavaScript coerces it to 0, so "" == 0 is true. The fix is to use === (strict equality): input === 0 would be false for an empty string, correctly logging 'Not a number'.
Related Resources
Related Lessons
- JavaScript Data Types
Learn about == vs ===.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.