Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Data Types  ›  Capstone Project

The typeof Operator

typeof operator 12 mintypeof returns a string naming a value's type, but reports null and arrays as "object", so those need dedicated checks.

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

Routing a value to the right handler

A function that must treat a title differently from a play count uses typeof to branch:

javascript

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":

javascript

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.

Guarding a playlist functionStep 1 of 4
  1. 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:

javascript

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

quick drill

What is typeof null?

quick drill

What is typeof [1, 2, 3]?

quick drill

What does typeof someGlobalFlag give when someGlobalFlag was never declared anywhere?

quick drill

What is typeof function () {}?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainA safe type check

A function should accept either an array of songs or null meaning no playlist yet. A teammate checks typeof songs === "object". Explain why that is not enough and write better checks.