Reading == by Its Rules
In this lesson, you read the co-op’s old dashboard page, which uses == everywhere, so that you
know what each == does before anyone replaces it. Its rainLabel() function labels school’s rain,
sent as the text "0.0" by old firmware, as dry, although Python’s "0.0" == 0 is False. ==
follows six rules:
- Same type:
==compares like===.0.2 == 0isfalseand0 == 0istrue. JavaScript’s booleans,trueandfalse, are lowercase, where Python writesTrueandFalse. nullandundefinedequal each other and nothing else, sonull == 0isfalse, much as Python’sNoneequals onlyNone.- A string next to a number becomes a number, so
"0.0" == 0istrue. Python’s==works across number types only, as in1 == 1.0, and a string never equals a number. - A boolean becomes a number first:
trueis1andfalseis0. Sotrue == 1istrue, as Python’sTrue == 1is, buttrue == "1"istrueas well, where Python’sTrue == "1"isFalse. Watch out:== trueisn’t a truthiness test, in Python either, where2 == TrueisFalse. Orchard’s old firmware sends its heater’s power level,2, which is truthy, buttruebecomes1, and2 == trueisfalse. - An object next to a primitive becomes a primitive first: an empty array becomes an empty
string, so
[] == ""istrue. How that works in full is a later topic. NaNequals nothing.
Replacing if (rain == 0) with if (Number(rain) === 0), converting first and then comparing
strictly as float(rain) == 0 would in Python, labels orchard’s missing reading dry.
Number(null) is 0, while Python’s float(None) raises a TypeError. The old line never
converted null: == checks for null and undefined before any conversion, so null == 0 was
false.
With a number on the other side, the relational operators <, >, <= and >= take the
converting path, so a check like rain >= 0 lets orchard’s missing reading through: null >= 0
and null <= 0 are both true. Watch out: they turn null into 0 and undefined into NaN,
which fails every comparison, with no error, where Python’s None >= 0 raises a TypeError.