Lesson 6 of 8
Tricky comparisons
- 12 min
- 4 checks
- 3 hints
- Go to task
Goal
Three comparisons that silently give the wrong answer
Explanation
When you compare with ==, JavaScript first converts both sides to the same type, so '' == 0 and '0' == 0 are both true. As far as it's concerned, an empty field and a field holding zero are the same thing. The === operator compares type and value with no conversion at all, which is why it should be your default.
NaN is the only value that isn't equal to itself, so the condition n === NaN is always false, even when n itself is NaN. Check for it with Number.isNaN(n) instead.
Objects are compared by reference, not by content: two objects that match in every property aren't equal unless they're the same object. Whatever arrives from the server is always a new object, so compare by a stable id.
Your task
Fix the three comparisons: make isEmpty stop treating '0' as empty, make parseQty return null for anything that isn't a number, and make inCart recognize a product by its id.
Checks
4 checks- The string "0" is a value, not empty
- NaN is caught, not let through
- Valid numbers pass through unchanged
- A product is matched by its id, not its reference