The typeof Operator
In short: typeof value returns a string naming the value's type at run
time — handy for branching on what you were given. It's mostly reliable,
with two famous blind spots you must know by heart: typeof null is
"object" (a decades-old bug kept for compatibility) and typeof on any
array is also "object". For those two, use === null and
Array.isArray() instead.
![typeof as a label machine: "Blue Hour" correctly comes out labelled "string", but both null and [1,2,3] are wrongly labelled "object" — with a note to use === null and Array.isArray() for those two](/api/assets/javascript/assets/4844b8d11ecfb021.png)
Routing a value to the right handler
A function that must treat a title differently from a play count uses
typeof to branch:
Every primitive answers typeof with its own name — "string",
"number", "boolean", "bigint", "symbol", "undefined" — which makes
this the fastest way to branch on ordinary values.
Guarding a playlist parameter
Now the two blind spots, in one function that must accept an array, or
null meaning "no playlist yet":
typeof null and typeof [1, 2, 3] are both "object" — so is a plain
{} — so typeof alone can't tell the three apart. === null catches the
first case exactly, and Array.isArray() is true only for real arrays,
never for null or a plain object. Together they cover every case
typeof would have blurred together.
The goal
Accept only a real array of songs.
A name that was never declared
typeof has one more quirk worth knowing: unlike reading the name
directly, it never throws, even if the name doesn't exist anywhere:
typeof notDeclaredAnywhere safely gives "undefined" instead of a
ReferenceError — handy for checking whether a global feature exists
before using it. And because typeof always returns a string, and the
type of any string is itself "string", typeof typeof 42 is "string".
The trap: the result is a string, so typeof x === number (no quotes)
compares against a variable named number, not the type. Always quote it:
typeof x === "number".
Quick practice
What is typeof null?
What is typeof [1, 2, 3]?
What does typeof someGlobalFlag give when someGlobalFlag was never declared anywhere?
What is typeof function () {}?
