Checking Instead of Catching
Joan’s Python script checks each donation against the donor’s pledge in the pledges file, by
trying the lookup and handling the KeyError.
D-117 has no pledge on file, so it prints No pledge on file for D-117, and the total stays 0.
Ported line by line, the lookup goes inside try, and catch (err) stands where except KeyError
stood:
const pledges = { "D-101": 50, "D-102": 25, "D-106": 75 };
const donor = "D-117";
let pledged = 0;
try {
pledged += pledges[donor];
} catch (err) {
console.log(`No pledge on file for ${donor}`);
}
console.log(pledged);
It logs only NaN, the not-a-number value, so the catch never ran:
NaN
A missing key isn’t an error in JavaScript: reading one gives undefined, JavaScript’s value for
nothing there, and += adds it to 0, which gives NaN. Neither step throws, so the catch is
skipped. In the real script, one missing pledge makes the trustees’ pledge total NaN, and no
error tells Joan.
Much of what raises in Python doesn’t throw in JavaScript. An index past the end of an array gives
undefined, not an IndexError, and 1 / 0 gives Infinity, with no ZeroDivisionError raised.
Watch out: a try around Number() catches nothing either, because Number("n/a") quietly gives
NaN; check the result instead.
Python could look first too, with if donor in pledges:. In JavaScript, looking first is the way,
because the lookup has nothing to throw. Object.hasOwn(pledges, donor) asks whether pledges
has the donor as a key. The try becomes an if, and the catch becomes the else
branch:
const pledges = { "D-101": 50, "D-102": 25, "D-106": 75 };
const donor = "D-117";
let pledged = 0;
if (Object.hasOwn(pledges, donor)) {
pledged += pledges[donor];
} else {
console.log(`No pledge on file for ${donor}`);
}
console.log(pledged);
It logs what Python prints:
No pledge on file for D-117
0
The if reports a missing pledge. When it should count as zero instead,
pledged += pledges[donor] ?? 0; replaces the whole if and else, like Python’s
pledged += pledges.get(donor, 0), and gives 0 for D-117.
Where they part: .get() checks the key, and ?? checks the value, so a stored null,
JavaScript’s other empty value, becomes 0 too, where Python’s .get() returns the stored None
unchanged.
So check with an if when a value might be missing, or default it with ??. Keep try and
catch for what really throws: parsing JSON, reading files, and errors you throw, which the next
section covers.
Next up: Look Up Each Donor’s Pledge, an exercise, where you’ll turn the pledges file’s text into pledges and look up each donor’s pledge.