Asking a Value’s Type With typeof
In this lesson, you ported two lines of the backup check that ask about a value’s type: the debug line, and the check that makes sure the settings file’s recipients are a list, not one address typed as a lone string.
- JavaScript has no
type()function. You writetypeofin front of a value instead. It’s an operator rather than a function, like Python’snot, so it needs no parentheses. - Python’s
type()gives you the class, so the debug line asks for its.__name__.typeofskips the class and answers with the name as a string, and the names are JavaScript’s own:stringwhere Python saysstr. - The type names:
intandfloatare both"number", sotypeof 2.5is"number"too.stris"string", andboolis"boolean", whose value is lowercasetrue. Where Python hasNone, JavaScript hasundefinedandnull. Two more,bigintandsymbol, complete the list of primitive types. - To check a type, compare the answer with the name in quotes:
typeof retries === "number"istrue, asisinstance(retries, int)isTruein Python. Python writes a type bare, buttypeof’s answer is a string: without the quotes,numberis an unknown name, and JavaScript stops with a reference error, its version of aNameError. - A primitive is a basic value rather than an object, where in Python even
3is anintobject. JavaScript lends a number methods such as.toFixed()when you call one. typeofhas an answer for each primitive type, and says"object"for almost everything else, arrays included. Sotypeof job.recipientsis"object", for an array as for a plain object likejob, and the"array"check never passes. Functions get an answer of their own,"function".typeof nullis"object"too, a long-standing quirk, so a check for"object"letsnullthrough.- To ask whether a value is an array, use
Array.isArray(), a method of JavaScript’s built-inArray. For the recipients, it saystrue, asisinstance()does in Python. typeofis liketype()only partway:type()andisinstance()work with any class, your own included, whiletypeofonly picks a name from its fixed list.
Here’s the debug line in the port, with the settings held in constants for now:
const bucket = "kestrel-db-backups";
const retries = 3;
const dryRun = true;
console.log(`Debug: bucket is ${typeof bucket}`);