Logic errors: code that runs perfectly and answers wrongly
The wrong operator, an inverted condition, a formula the right way round but backwards.
What is logic error?
The program does exactly what you wrote, and what you wrote is not what you meant. There is no error message and no crash — only a wrong answer, which is why these are the hardest to spot and the most likely to reach production.
Why it happens
Boolean logic and arithmetic are easy to invert without it looking wrong. || instead of && lets either side pass. any() instead of all() accepts one match instead of requiring every one. A reversed subtraction flips the sign of every result while the magnitude stays plausible. Short-circuit guards placed after the thing they guard read as safe while doing nothing.
How to recognise it
- The magnitude is right but the sign is wrong.
- It is correct for uniform input and wrong for mixed input.
- A guard clause exists but the crash it prevents still happens.
- Boundary values are handled inconsistently at each end.
Errors and symptoms this causes
- wrong output but no error
- and vs or in condition
- any vs all
- result has the wrong sign
- condition always true
How to fix it
Build a small truth table for any condition with more than one term, and test each branch. Check one case per direction for signed results. Read guards in evaluation order, not reading order — `and` short-circuits left to right, so a guard on the right protects nothing.
Practise logic errors
Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.