Checking for Empty Values
In this lesson, you ported the two checks that warn when nobody will hear about a failed backup:
the one for an empty NOTIFY_EMAIL, and the one for an empty recipients list in the new server’s
settings file.
- Where Python writes
not, JavaScript writes!in front of the value. Likenot, it answerstrueorfalse, in lowercase. Inside theif,console.log()doesprint()’s job. - For strings,
null, andundefined, truthiness carries over: an empty string andundefinedcount as false, as an empty string andNonedo in Python. So the notify check warns withNOTIFY_EMAILempty or unset, as the Python does, and the message’s “empty” covers unset too. - Values that count as false in a condition are falsy, and every other value is truthy. MDN’s Falsy page keeps the full list.
- JavaScript’s falsy values are
false,0, the empty string"",nullandundefined, andNaN, the “not a number” value you get by adding one to a missing retry count. Two rare ones also count: negative zero (-0) and the zero of bigint (0n), a type for huge whole numbers you won’t need here. - Any text that isn’t empty is truthy, even
"false", in both languages. - On JavaScript’s falsy values, Python agrees on all but one: its
float("nan")is truthy, butNaNis falsy in JavaScript. Python’s own falsy values also include its empty containers, such as an empty list or dict, and that’s where the two languages part. - An array is an object in JavaScript, empty or not, and every object is truthy. Python asks a list
or a dict whether it’s empty, but JavaScript’s falsy list is a fixed set of primitive values, plain
values like strings and numbers, and it never looks inside an object. So
!job.recipientsisfalsefor an empty array, and the line-by-line port ofif not job["recipients"]:prints nothing. - Ask the question you mean instead: an array’s
.lengthcounts its items, like Python’slen(), sojob.recipients.length === 0istruefor an empty array. Where Python’s habit isif not, a JavaScript developer checks the length. - An empty object is truthy too, and its
.lengthisundefined, so checking it never warns either. Count its keys instead, aslen()does for a dict:Object.keys(obj).length === 0, whereObject.keys()gives you an array of an object’s keys, and you check the array’s length is zero. Objects get a course of their own later on. - The rule: for a string or a missing value,
if (!notifyEmail)works as Python’sif not notify_email:does. For an array, check its length:job.recipients.length === 0. For an object, count its keys:Object.keys(obj).length === 0.
Here’s the notify check in the port:
const notifyEmail = process.env.NOTIFY_EMAIL;
if (!notifyEmail) {
console.log(
"Warning: NOTIFY_EMAIL is empty,",
"so nobody hears about failures.",
);
}