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 a 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.
Error guides caused by this pattern
All error guides →In-depth guides for common exceptions and runtime errors triggered by logic errors, with working fixes and real-world examples:
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.
Breaks vs Works Example
Breaks
// JavaScript: inverted Boolean condition
if (role !== 'admin' || role !== 'editor') {
denyAccess(); // Bug: Always true! An admin is not an editor.
}Works
// JavaScript: conjunction ensures user is neither
if (role !== 'admin' && role !== 'editor') {
denyAccess(); // Correctly allows admins and editors
}💡 Remember De Morgan's laws: !(A && B) is !A || !B; to exclude both options, use AND (&&).
Practise logic errors
Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.
has_word(text, word) returns True only when word appears as a whole word. Example: has_word("cat nap", "cat") → True, has_word("I love cats", "cat") → False.
Logic error
inStock(items, name) returns true if the product is in the list. Example: inStock(["pen", "ink"], "pen") → true.
Logic error
sanitize_phone_number(phone) strips all hyphens from a phone number string. Example: sanitize_phone_number("123-456-7890") → "1234567890".
Logic error
pair_users_and_badges(users, badges) pairs users with badges, filling missing values with "none". Example: pair_users_and_badges(["a", "b"], [1]) → [["a", 1], ["b", "none"]].
Logic error
total_price(prices) adds up every price. Example: total_price([10, 20, 30]) → 60.
Logic error
sum_until_stop(readings) adds readings until it meets -1, which means "stop". Anything after -1 is ignored. Example: sum_until_stop([3, 4, -1, 10]) → 7.
Logic error
format_invoice_number(numStr) pads a number string with leading zeroes to a length of 5. Example: format_invoice_number("42") → "00042".
Logic error
highestPrice(prices) returns the biggest price. Example: highestPrice([3, 7, 2]) → 7.
Logic error
sort_prices_ascending(prices) returns a new array with numbers sorted in ascending numerical order without modifying the original array. Example: sort_prices_ascending([100, 25, 5]) → [5, 25, 100].
Logic error
drop_first_item(items) returns a new array containing all elements except the first. Example: drop_first_item(["a", "b", "c"]) → ["b", "c"].
Logic error
find_status_code(codes, target) returns the matching number from codes, or -1 if target is not in the array. Example: find_status_code([10, 0, 20], 0) → 0.
Logic error
count_file_lines(file_content) counts lines in file_content, returning 0 for empty strings. Example: count_file_lines('a\nb\n') → 2.
Logic error
longest_word(words) returns the longest word. Example: longest_word(["hi", "hello", "hey"]) → "hello".
Logic error
get_retry_limit(override) returns override count, falling back to 3 only if override is None. Example: get_retry_limit(0) → 0.
Logic error
pop_undo_action(history) pops and returns the last action from history, returning None if history is empty. Example: pop_undo_action([]) → None.
Logic error
count_words(text) counts the total words in a string, ignoring irregular consecutive spaces. Example: count_words("hello world") → 2.
Logic error
evaluate_access_tier(user) returns "Privileged" if user.role is "admin", returning "Standard" otherwise. Example: evaluate_access_tier({ role: "guest" }) → "Standard".
Logic error
find_lowest_fee(fees) returns the lowest fee from fees, returning 0 if the list is empty. Example: find_lowest_fee([]) → 0.
Logic error
round_penalty_score(score) rounds score using standard half-away-from-zero rounding. Example: round_penalty_score(-2.5) → -3.
Logic error
subtract_inventory_counts(stock, sold) subtracts sold items from stock, removing items that reach zero. Example: subtract_inventory_counts({"apple": 2}, {"apple": 2}) → {}.
Logic error
purge_inactive_sessions(sessions) removes all keys where active is False and returns the cleaned dictionary. Example: purge_inactive_sessions({"s1": True, "s2": False}) → {"s1": True}.
Logic error
average_of_two(a, b) returns the average of two marks. Example: average_of_two(4, 6) → 5.
Logic error
calculate_net_payout(gross_amount, processing_fee) subtracts processing_fee from gross_amount rounded to 2 decimal places. Example: calculate_net_payout(1.1, 0.9) → 0.2.
Logic error
top_scorer(scores) takes a dict of names and scores and returns the name with the highest score. Example: top_scorer({"asha": 90, "ravi": 95, "zoe": 70}) → "ravi".
Logic error
find_missing_required_keys(provided_keys, required_keys) returns the missing required keys in sorted order. Example: find_missing_required_keys(["id"], ["id", "email"]) → ["email"].
Logic error
extract_grouped_keys(items) returns the unique sorted group keys from items. Example: extract_grouped_keys(["a", "b", "a"]) → ["a", "b"].
Logic error
sort_names_alphabetical(names) sorts strings in case-insensitive alphabetical order. Example: sort_names_alphabetical(["zebra", "apple", "Banana"]) → ["apple", "Banana", "zebra"].
Logic error
deduplicate_users_by_id(users) removes duplicate user objects sharing the same id. Example: deduplicate_users_by_id([{ id: 1 }, { id: 1 }]) → [{ id: 1 }].
Logic error
check_answer(answer) marks the answer to "What is the capital of France?", ignoring capitals and extra spaces. Example: check_answer("Paris ") → True.
Logic error
An AI assistant wrote this FizzBuzz. fizzbuzz(n) returns "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and otherwise the number as text. Example: fizzbuzz(15) → "FizzBuzz".
Logic error
generate_index_range(length) generates an array of sequential integers from 0 to length - 1. Example: generate_index_range(3) → [0, 1, 2].
Logic error
summarize_stream(numbers) returns a dictionary with the count and sum of numbers. Example: summarize_stream([10, 20]) → {"count": 2, "sum": 30}.
Logic error
format_tag_summary(tags) returns "No tags" if tags is null, undefined, or empty, returning "N tags" otherwise. Example: format_tag_summary([]) → "No tags".
Logic error
count_words(text) counts the words, however many spaces are between them. Example: count_words("hello world") → 2.
Logic error
strip_log_extension(filename) removes the trailing ".log" extension from a filename. Example: strip_log_extension("catalog.log") → "catalog".
Logic error
clamp_percentage(value) constrains value to the range 0 to 100 inclusive. Example: clamp_percentage(150) → 100.
Logic error
count_vowels(text) counts the vowels, capital or small. Example: count_vowels("Apple") → 2.
Logic error
rank(students) takes [name, score] pairs and returns the names from highest score to lowest. Example: rank([["asha", 72], ["ravi", 95], ["zoe", 60]]) → ["ravi", "asha", "zoe"].
Logic error
truncate_coordinate(val) removes the fractional digits of val, rounding toward zero. Example: truncate_coordinate(-1.7) → -1.
Logic error
extract_trailing_characters(text, count) returns the last count characters of text. Example: extract_trailing_characters("hello_world", 5) → "world".
Logic error
swap(pair) returns the two values in the opposite order. Example: swap([1, 2]) → [2, 1].
Logic error
reverse_words(sentence) reverses the order of the words but keeps each word readable. Example: reverse_words("hello world") → "world hello".
Logic error
serve_next(queue) removes and returns the person who has waited longest, at the front. Example: serve_next(["asha", "ravi", "zoe"]) → "asha".
Logic error
count_passing(scores) counts the scores of 40 or more. Example: count_passing([72, 35, 90]) → 2.
Logic error
to_fahrenheit(celsius) converts Celsius to Fahrenheit. Example: to_fahrenheit(100) → 212, to_fahrenheit(0) → 32.
Logic error
calculate_discounted_price(price, discount) subtracts discount from price rounded to 2 decimal places. Example: calculate_discounted_price(0.3, 0.2) → 0.1.
Logic error
is_valid_cart_container(items) returns True if cart was successfully initialized as an object, even if items is empty. Example: is_valid_cart_container([]) → True.
Logic error
is_weekend(day) returns True for "Saturday" and "Sunday", and False for other days. Example: is_weekend("Monday") → False.
Logic error
calculate_discounted_total(subtotal, promoPercent) applies promoPercent to subtotal, falling back to 15% only if promoPercent is missing or undefined. Example: calculate_discounted_total(100, 0) → 100.
Logic error
count_csv_tags(tagString) returns the number of comma-separated tags in a string, returning 0 for an empty string. Example: count_csv_tags("") → 0.
Logic error
sort_contacts(names) sorts names A to Z, ignoring capitals. Example: sort_contacts(["bob", "Carl", "alice"]) → ["alice", "bob", "Carl"].
Logic error
divide_truncate_toward_zero(a, b) divides a by b, truncating the fractional part toward zero. Example: divide_truncate_toward_zero(-7, 2) → -3.
Logic error
has_custom_field(payload, fieldName) returns true only if fieldName is an own property of payload, ignoring inherited prototype properties. Example: has_custom_field({}, "toString") → false.
Logic error
isEven(n) returns true when n is even and false when it is odd. Example: isEven(4) → true, isEven(3) → false.
Logic error
sort_numbers_ascending(numbers) sorts numbers in ascending order using a custom comparator. Example: sort_numbers_ascending([10, 2, 5, 1]) → [1, 2, 5, 10].
Logic error
build_api_endpoint_path(base_path, sub_path) joins base_path and sub_path into a complete path string. Example: build_api_endpoint_path("/api/v1", "/users") → "/api/v1/users".
Logic error
qualifiesForFreeShipping(total) returns true when the order is 50 or more. Example: qualifiesForFreeShipping(50) → true, qualifiesForFreeShipping(49.99) → false.
Logic error
safe_find_index(items, target) returns the index of target in items, returning -1 if missing. Example: safe_find_index([1, 2], 99) → -1.
Logic error
create_user_role_buckets(roles, initial_admin) initializes an empty list for each role and adds initial_admin to the first role. Example: create_user_role_buckets(["admin", "guest"], "alice") → {"admin": ["alice"], "guest": []}.
Logic error
remove_even_numbers(numbers) removes all even integers and returns a list containing only odd numbers. Example: remove_even_numbers([2, 4, 6]) → [].
Logic error
are_all_accounts_verified(accounts) returns True only if accounts is non-empty and every account is verified. Example: are_all_accounts_verified([]) → False.
Logic error
round_order_rating(rating) rounds rating to the nearest integer using standard round-half-up math. Example: round_order_rating(2.5) → 3.
Logic error
find_user_position(users, id) returns the index of the user object with matching id, or -1 if missing. Example: find_user_position([{ id: 1 }, { id: 2 }], 2) → 1.
Logic error
top_three(scores) returns the 3 highest scores, best first. Example: top_three([50, 90, 70, 80]) → [90, 80, 70].
Logic error
isPalindrome(word) returns true if the word reads the same backwards, ignoring capitals. Example: isPalindrome("Racecar") → true.
Logic error
extract_first_digits(text) returns the first sequence of digits found anywhere in text. Example: extract_first_digits("order_123") → "123".
Logic error
contains(items, target) returns True if target is anywhere in the list. Example: contains([4, 8, 15], 8) → True.
Logic error
hasNegative(nums) returns true if any number is negative. Example: hasNegative([5, -3, 8]) → true.
Logic error
sum_evens(nums) adds up only the even numbers. Example: sum_evens([1, 2, 3, 4]) → 6.
Logic error
sortNumbers(arr) sorts numbers from smallest to largest. Example: sortNumbers([10, 2, 30]) → [2, 10, 30].
Logic error
create_safe_redirect_url(targetUrl) encodes targetUrl as a query parameter in a redirect link. Example: create_safe_redirect_url("https://example.com/oauth?code=123") → "https://api.com?redirect=https%3A%2F%2Fexample.com%2Foauth%3Fcode%3D123".
Logic error
double_all(prices) doubles every price. Example: double_all([1, 2, 3]) → [2, 4, 6].
Logic error
calculate_total_pages(total_items, page_size) returns the total number of pages required to display all items. Example: calculate_total_pages(11, 5) → 3.
Logic error
deduplicate_preserve_order(items) removes duplicates while preserving the original appearance order. Example: deduplicate_preserve_order(["b", "a", "c", "a"]) → ["b", "a", "c"].
Logic error
order_total(prices) adds up every price. Example: order_total([5, 10, 15]) → 30.
Logic error
can_checkout(cart_total, has_valid_payment) returns True only when the cart is not empty and the payment is valid. Example: can_checkout(50, True) → True, can_checkout(50, False) → False.
Logic error
find_top_score(scores) returns the highest score from scores, returning 0 if scores is empty. Example: find_top_score([]) → 0.
Logic error
get_latest_breadcrumb(breadcrumbs) returns the final item from breadcrumbs using modern indexing. Example: get_latest_breadcrumb(["home", "docs", "api"]) → "api".
Logic error
strip_url_protocol(url) removes the leading "https://" protocol prefix from a URL string. Example: strip_url_protocol("https://threat.com") → "threat.com".
Logic error
pop_with_fallback(items) removes and returns the last element from items, returning -1 only if items was empty. Example: pop_with_fallback([0]) → 0.
Logic error
is_matching_account_id(account_id, target_id) returns True if account_id matches target_id by value. Example: is_matching_account_id(1000, 1000) → True.
Logic error
get_max_score(scores) returns the highest score from scores, returning 0 if the array is empty. Example: get_max_score([]) → 0.
Logic error
are_all_items_in_stock(items) returns true only if items contains at least one item and every item is in stock. Example: are_all_items_in_stock([]) → false.
Logic error
has_user_by_id(users, targetId) returns true if a user with targetId exists in users. Example: has_user_by_id([{ id: 'u1' }], 'u1') → true.
Logic error
is_prime(n) returns True if n is a prime number. Example: is_prime(7) → True, is_prime(8) → False, is_prime(1) → False.
Logic error
remove_item_at_index(items, index) removes the item at index and returns the shortened array. Example: remove_item_at_index(["apple", "banana", "cherry"], 1) → ["apple", "cherry"].
Logic error
get_lowest_price(prices) returns the minimum price from prices, returning 0 if the list is empty. Example: get_lowest_price([]) → 0.
Logic error
discard_oldest_log(logs) returns a new array with the first log removed, without mutating logs. Example: discard_oldest_log(["a", "b", "c"]) → ["b", "c"].
Logic error
calculate_remaining_balance(balance, payment) subtracts payment from balance, rounded to 2 decimal places. Example: calculate_remaining_balance(1.0, 0.9) → 0.1.
Logic error
flatten_nested_categories(categories) flattens a deeply nested array of category names into a single flat array. Example: flatten_nested_categories([1, [2, [3, 4]]]) → [1, 2, 3, 4].
Logic error
join_endpoint_path(parts) joins non-empty path segments with a single slash. Example: join_endpoint_path(["api", null, "users"]) → "api/users".
Logic error
mentions(text, word) returns True if word appears anywhere in text. Example: mentions("hello world", "hello") → True.
Logic error
filter_valid_inventory(items) keeps all items that have a defined count property, including zero. Example: filter_valid_inventory([{ id: 1, count: 0 }]) → [{ id: 1, count: 0 }].
Logic error
isAvailable(item) is true only when the item is in stock and not discontinued. Example: isAvailable({ inStock: false, discontinued: false }) → false.
Logic error
safe_ratio(a, b) returns True when a / b is more than 1. If b is 0 it returns False instead of crashing. Example: safe_ratio(4, 2) → True, safe_ratio(1, 0) → False.
Logic error
groupByLength(words) groups words by their length. Example: groupByLength(["ab", "cd", "x"]) → { 1: ["x"], 2: ["ab", "cd"] }.
Logic error
highest_temp(readings) returns the highest temperature of the day. Example: highest_temp([12, 18, 15]) → 18, highest_temp([-5, -2, -9]) → -2.
Logic error
is_admin(role) returns True for "admin" in any mix of capitals. Example: is_admin("Admin") → True, is_admin("user") → False.
Logic error
age_on(birth_iso, today_iso) returns how old someone is on a given date. Example: age_on("2000-12-25", "2024-06-01") → 23.
Logic error
override_tenant_port(default_config, new_port) overrides db port in a cloned config without mutating default_config. Example: override_tenant_port({'db': {'port': 5432}}, 5433) → [5433, 5432].
Logic error
An AI assistant wrote this for a classic interview question. removeAll(arr, item) removes every copy of item from the array. Example: removeAll([1, 2, 2, 3], 2) → [1, 3].
Logic error
An AI assistant wrote this for a classic interview question. has_pair_sum(numbers, target) returns True if two different numbers in the list add up to target. Example: has_pair_sum([1, 2, 3], 5) → True, has_pair_sum([5], 10) → False.
Logic error
An AI assistant wrote this to find the second-best score in a quiz. second_highest(scores) returns the second-highest different score. Example: second_highest([70, 90, 80]) → 80, second_highest([90, 90, 80]) → 80.
Logic error
checkout(total, pct) takes pct percent off the total. This project has two files: cart.py and pricing.py. Example: checkout(200, 50) → 100.
Logic error
dayType(day) returns "weekend" for Saturday and Sunday, and "weekday" for any other day. Example: dayType("Saturday") → "weekend".
Logic error
An AI assistant wrote this for a classic interview question. is_anagram(a, b) returns True when both words use the same letters, the same number of times. Example: is_anagram("listen", "silent") → True, is_anagram("aab", "abb") → False.
Logic error
remove_word(words, target) removes every copy of target. Example: remove_word(["spam", "eggs", "spam"], "spam") → ["eggs"].
Logic error
An AI assistant wrote this for a classic interview question. is_balanced(text) returns True when every ( is closed by a ) that comes after it. Example: is_balanced("(())") → True, is_balanced(")(") → False.
Logic error
is_leap_year(year) returns True for leap years. The rule: divisible by 4, but not by 100, unless also divisible by 400. Example: 2024 → True, 1900 → False, 2000 → True.
Logic error
first_pair(nums, target) returns the first pair, from the left, that adds up to target. Example: first_pair([1, 2, 3, 4], 5) → [1, 4].
Logic error
find_duplicates(nums) lists each repeated value once, in the order it first appears. Example: find_duplicates([1, 2, 2, 3]) → [2].
Logic error
grade(score) returns "A" for 90 and above, "B" for 80–89, "C" for 70–79, "D" for 60–69 and "F" below 60. Example: grade(95) → "A".
Logic error
largest_gap(nums) returns the biggest jump between neighbouring numbers in a list that goes up. Example: largest_gap([1, 5, 6]) → 4.
Logic error
is_registered(users, name) checks if a username exists. users maps IDs to names, like {"u1": "asha", "u2": "ravi"}. Example: is_registered(users, "asha") → True.
Logic error
all_positive(nums) returns True only when every number is above zero. Example: all_positive([1, -2]) → False.
Logic error
percentChange(oldValue, newValue) returns the change as a percentage of the old value. Example: percentChange(100, 150) → 50.
Logic error
cartTotal(items) adds up price × quantity for every item. This project has two files: cart.js and lineItem.js. Each item looks like { price: 10, quantity: 2 }. Example: [{ price: 10, quantity: 2 }, { price: 5, quantity: 1 }] → 25.
Logic error
Stuck on your own code?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.