Lesson 6 of 8

Tricky comparisons

Goal

Three comparisons that silently give the wrong answer

01

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.

02

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
  1. The string "0" is a value, not empty
  2. NaN is caught, not let through
  3. Valid numbers pass through unchanged
  4. A product is matched by its id, not its reference
03

Hints

0/3
Track lessons0 of 8 done

Learn how to read an error message, check inputs before you use them, and catch the errors worth handling.

Intermediate level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/4

Press “Run and check” to grade your code.

4 checks listed under “Your task”.

Track lessons0 of 8 done

Learn how to read an error message, check inputs before you use them, and catch the errors worth handling.

Intermediate level, 8 lessons, 1.5 hours in total.