JS Typeof
typeof returns a string describing a value's type. It's the primary way to check primitives at runtime — though it has one infamous quirk.
The full set of return values
| Value | typeof returns |
|---|---|
"text" | "string" |
42 | "number" |
42n | "bigint" |
true | "boolean" |
undefined | "undefined" |
Symbol("id") | "symbol" |
function(){} | "function" |
null | "object" ← historic bug, kept for compatibility |
{}, [], new Date() | "object" |
Better tests for the edge cases
JS
// Test for null specifically x === null // Test for an array Array.isArray(x) // Test for a "plain" object (not array, not Date, etc.) x !== null && typeof x === "object" && x.constructor === Object // Test for a specific class x instanceof Date // Test for any number that is finite Number.isFinite(x)
Safe usage on undeclared variables
typeof is the only operator that doesn't throw when used on an undeclared variable:
JS
typeof doesNotExist // "undefined" — does NOT throw doesNotExist // ReferenceError
Tip: For class instances, prefer
instanceof. For arrays, prefer Array.isArray. Reach for typeof only for primitives and "function".Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Typeof!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Test whether a value is a primitive number.
if (
x === 'number') { /* … */ }
The keyword same as the topic name.
Discussion
Loading…