JavaScriptEasy
What is the typeof operator?
typeof returns a string describing the type of a value: "string", "number", "bigint", "boolean", "undefined", "symbol", "function" or "object".
It is mainly used for runtime checks before you use a value, for example to see whether an optional callback was passed or a global exists.
Results worth remembering
typeof null→"object". A bug from the first version of JavaScript that can never be fixed without breaking the web. Checkvalue === nullinstead.typeof []→"object". UseArray.isArray(value).typeof NaN→"number". UseNumber.isNaN(value).typeof class {}→"function". Classes are functions underneath.typeof undeclaredVariable→"undefined", with no error. That made it the classic way to feature-detect globals. (Variables in the TDZ still throw.)
Better tools for specific checks
Array.isArray(x)for arrays.x instanceof Date(orMap,Set, a class) for objects created by a constructor in the same realm.Object.prototype.toString.call(x)returns"[object Date]","[object RegExp]"and so on, and works across iframes.
Interview tip
Write a small getType helper that handles null and arrays. It shows you know the quirks and how to work around them.
Code example
js
1console.log(typeof "hi"); // "string"2console.log(typeof 42); // "number"3console.log(typeof 42n); // "bigint"4console.log(typeof true); // "boolean"5console.log(typeof undefined); // "undefined"6console.log(typeof Symbol()); // "symbol"7console.log(typeof (() => {})); // "function"8console.log(typeof null); // "object" <- quirk9console.log(typeof [1, 2]); // "object" <- use Array.isArray10console.log(typeof notDeclaredAnywhere); // "undefined", no error1112// A precise type helper13function getType(value) {14 if (value === null) return "null";15 if (Array.isArray(value)) return "array";16 if (typeof value === "object") return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();17 return typeof value;18}19console.log(getType(null), getType([]), getType(new Date()), getType(/x/), getType(new Map()));20// null array date regexp map
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.