Checking Instead of Catching
Joan’s Python script checks each donation against the donor’s pledge the usual Python way,
easier to ask forgiveness than permission: it tries the lookup and handles the miss. The real
script adds up every row’s pledge, so the trustees can compare pledges with what came in; here,
it’s one donor. For D-117, who has no pledge on file, the KeyError sends it
to the except block, so it prints No pledge on file for D-117 and the total stays 0.
The line-by-line port to JavaScript wraps the lookup in try and catch (err), but it logs only
NaN. A missing key isn’t an error in JavaScript: reading one gives undefined, and += adds
undefined to 0, which JavaScript turns into NaN, the not-a-number value. Python’s nearest
match, 0 + None, would raise a TypeError. Nothing throws, so the catch block never runs.
One missing pledge makes the whole pledge total NaN, and no error says so.
Much of what raises in Python doesn’t throw in JavaScript. An index past the end of an array gives
undefined, where Python raises IndexError, and 1 / 0 gives Infinity, where Python raises
ZeroDivisionError. Watch out for bad text too: a try around Number() won’t catch it, because
Number("n/a") quietly gives NaN, so check the result instead.
In Python, you could look before you leap, with if donor in pledges:. In JavaScript, looking
first is the way, because the lookup has nothing to throw. Object.hasOwn() asks whether an
object has a key. It checks only keys set on the object itself, which is what you want here:
that’s all you need about it for now. The try becomes an if, and the
catch becomes the else branch: