The typeof operator is the built-in type checker in JavaScript, and it works well on everything except one famous case. Knowing the small set of answers it can give, the null quirk that trips up every beginner once, and the three tools that handle arrays and class instances correctly will save you a lot of guesswork.
The previous lesson in this module covered "Booleans, null and Missing Values Explained", and this lesson is the last one in the JavaScript Variables and Data Types module.
What does typeof return?
It always returns a string, and that string is always one of a small fixed set of values. These are the answers for every value that you will meet in ordinary JavaScript.
const values = [
["text", "hello"],
["number", 42],
["bigint", 10n],
["boolean", true],
["undefined", undefined],
["null", null],
["array", [1, 2]],
["object", { a: 1 }],
["function", function noop() {}],
["class", class Order {}],
["symbol", Symbol("id")],
];
for (const [label, value] of values) {
console.log(label, "->", typeof value);
}
The results are worth reading twice. Strings, numbers, bigints, booleans, undefined, and symbols each report themselves. Arrays report "object", because an array is an object underneath. Plain objects report "object" as well. Functions report "function", and so do classes, because a class is a function that produces objects when you call new on it, and typeof reports the function part.
Why does typeof null return object?
This is the famous one. typeof null returns "object", and it is a genuine bug rather than a deliberate design decision.
console.log(typeof null); // "object", the bug
console.log(null instanceof Object); // false
console.log(Object.prototype.toString.call(null)); // "[object Null]"
The story goes that the original implementation of JavaScript tagged each value with a type marker in the low bits of a machine word, and it used a special marker for objects. null was represented by that marker, so the check for objects caught it as well. Fixing it properly would have broken every site on the web that relied on the behaviour, so the language kept it and the specification now documents it as an intentional quirk.
You can detect the case correctly, and the second and third lines show you how. null instanceof Object is false, because null is not an object at all. And Object.prototype.toString.call(null) gives you the honest tag, which is [object Null].
How do I check whether a value is an array?
With Array.isArray. It is exact, it works across different browser windows, and it does not have the problems that the alternatives have.
class Order {}
console.log(Array.isArray([])); // true
console.log(Array.isArray({ length: 0 })); // false
console.log(Array.isArray("not an array")); // false
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true
console.log(new Order() instanceof Order); // true
console.log(Object.prototype.toString.call([])); // "[object Array]"
instanceof asks whether the prototype chain of an object includes a particular constructor. That makes it perfect for your own classes, so new Order() instanceof Order is true. It is unreliable for arrays, because an array that was created in a different window or inside an iframe has a different Array constructor and fails the check. Array.isArray has no such problem, and that is why it is the one to use.
Object.prototype.toString.call(value) is the most general tool of the three. It returns a tag such as "[object Array]", "[object Date]", or "[object Null]", and it works for the built-in types that typeof lumps together. Reach for it when you need to tell apart things that typeof cannot separate.
Does typeof throw on an unknown variable?
No, and this is a special case in the language. typeof on a name that does not exist returns "undefined" instead of raising a ReferenceError.
console.log(typeof neverDeclared); // "undefined", and no error
console.log(typeof someUndeclaredName); // "undefined"
// Reading the name itself does throw.
try {
console.log(someUndeclaredName);
} catch (error) {
console.log("reading it:", error.constructor.name);
}
The first two lines print undefined, and the third one prints reading it: ReferenceError. That special case exists so that you can check whether a global exists without wrapping the check in a try block. It does not extend to property access, because typeof obj.missing is safe while typeof obj.missing.deeper throws. The engine has to read obj.missing first, and that gave you undefined.
Which checks belong to the Number type?
JavaScript has both a global isNaN and a Number.isNaN, and they are not the same function. The global one converts its argument first, so it really means "does this turn into a number that is not a number".
console.log(isNaN("hello")); // true, because "hello" turns into NaN
console.log(Number.isNaN("hello")); // false, because it is a string and not NaN
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(undefined)); // false
console.log(Number.isInteger(42)); // true
console.log(Number.isInteger(42.5)); // false
console.log(Number.isFinite(1 / 0)); // false
Number.isNaN is the one you want. It answers the question "is this value actually NaN" without converting anything, so a string that merely looks un-numeric does not trip it. The same pattern holds for Number.isInteger and Number.isFinite. The Number. versions never convert their argument, and the global versions do.
What if you cannot control what you are given?
Sometimes a value comes from a third party, such as a form, an API response, or a URL parameter, and you cannot be certain what shape it has. Instead of guessing its type, check whether it has the behaviour that you need. This is called duck typing. If it walks and quacks like a list, you can treat it like a list.
function countItems(value) {
if (value && typeof value.length === "number") {
return value.length;
}
return 0;
}
console.log(countItems([1, 2, 3])); // 3
console.log(countItems("hello")); // 5
console.log(countItems({ length: 2 })); // 2
console.log(countItems(null)); // 0
The guard does two jobs at once. The value && part stops the function from throwing when the value is null or undefined, and the typeof value.length part confirms that there is a numeric length to read. Notice that { length: 2 } passes the check even though it is not a list. Duck typing checks for the capability that you need, and if a plain object with a length property is acceptable to your code, then that is fine.
You will meet this style again in the module about objects, because typeof value.length is really a property access, and property access is where most of the type surprises in JavaScript come from.
Which check should you reach for?
| You want to know | Use |
|---|---|
Is this a string, number, boolean, bigint, symbol or undefined? | typeof value |
Is this null? | value === null |
| Is this an array? | Array.isArray(value) |
| Is this an instance of my class? | value instanceof MyClass |
| What exact built-in type is this? | Object.prototype.toString.call(value) |
| Is this NaN? | Number.isNaN(value) |
| Is this a whole number? | Number.isInteger(value) |
The one rule to take away is that typeof is a good first check and a poor final one. It tells the primitives you care about apart, and it puts everything that is object-shaped into a single bucket. Whenever the distinction matters, use a more specific check.
typeofreturns"object"for arrays, objects,null, andRegExpalike. Only the first two are really objects.typeof null === "object"is a permanent quirk of the language, so test for null withvalue === null.- Classes report as
"function", because a class is a constructor function. typeofon an undeclared name is safe and returns"undefined", while reading the name itself is not safe.- Prefer the
Number.is*family over the globalisNaNandisFinite, which convert their arguments first.
Try it yourself: write a function describeType(value) that returns a precise label for any input. Return "null", "array", "date", "plain object", or the typeof result for everything else. Test it with null, [], new Date(), {}, 42, and "text". Then remove the special cases one at a time and watch typeof collapse the distinctions that you cared about back into a single "object".