Comparing With === Instead of ==
In this lesson, you ported the backup check’s one comparison and saw that JavaScript’s ==
converts types before comparing, as + and * do, where Python’s == doesn’t.
- Python’s
==never treats text as equal to a number: the retry count as the text"5"and as the number5compareFalse. In the port,process.envholds the settings, and as inos.environ, every value that’s set is text. The retry count goes throughNumber(), its default for an unset variable left for later. - The flag’s line, ported with
==, works on the new server, because both sides of its comparison are text. When both sides are text,==compares the way Python’s does. JavaScript’strueandfalseare lowercase, where Python writes a capital. - When the types don’t match,
==converts first, so"5" == 5istrue. As a test of how far that goes,"0" == falseistruetoo:==turns both sides into numbers,falseinto0and the text"0"into0. Python also treatsFalseas zero, but it never turns text into a number. "0" == falseis a comparison, not a truth test: in anif, the text"0"still counts as true. Empty text turns into zero as well, as it does withNumber(), so0 == ""istrue. Python saysFalseto"5" == 5,"0" == False, and0 == ""alike.- With
==, text passes for a number: a retry count left as text would still equal5, so the comparison hides the missing conversion. ===, the operator you’ve used to check fornullandundefined, never converts. For text, numbers, and booleans, it’s true only when both sides have the same type and the same value, so text never equals a number, as in Python."5" === 5,"0" === false, and0 === ""are allfalse.==is called loose equality, and===strict equality. The full rules for loose equality come later.- The flag’s line worked with
==, but===gives Python’s answers here, and you don’t have to check both sides’ types to trust it, so it’s what JavaScript developers write by default. To compare a setting as a number, convert it withNumber()first:Number("5") === 5istrue. - Not-equals comes in the same two kinds:
!=converts, so"5" != 5isfalse, and!==doesn’t, so"5" !== 5istrue, as Python’s"5" != 5isTrue. - The rule: write
===and!==everywhere, and convert text withNumber()before you compare it as a number. Loose equality’s one use on purpose isx == null, which catchesnullandundefinedtogether.
Here’s the port’s flag and retry count, written the JavaScript way:
const dryRun = process.env.DRY_RUN === "1";
const retries = Number(process.env.BACKUP_RETRIES);
console.log(`Dry run: ${dryRun}`);
console.log(`Up to ${retries + 1} attempts`);