typeof & instanceof
Two type checks that answer different questions -- primitive tags versus prototype membership.
Syntax
typeof value // -> string tag
obj instanceof Ctor // -> booleantypeof asks 'what primitive tag does this have?' and returns a string. instanceof asks 'is this object built from that constructor?' by walking the prototype chain.
typeof cheat sheet and its two traps
typeof null === 'object'-- a 26-year-old bug preserved forever.typeof function(){} === 'function'-- the only object subtype typeof distinguishes.
instanceof and the frame problem
[] instanceof Array is true, but an array from a different iframe or worker fails the check because it has a different Array. For arrays specifically, use Array.isArray(), which is realm-safe.
console.log(typeof 42, typeof 'x', typeof undefined);
console.log([] instanceof Array, Array.isArray([]));Example
Loading editor…
Press Run to execute the code.
When to use it
- Guard a function by checking typeof input === 'string' before calling string methods on it.
- Verify that a value received from a factory is an instance of the expected class before using its methods.
- Use instanceof to branch between handling a native Error and a custom AppError subclass.
More examples
typeof for primitive guards
Uses typeof to validate a function argument type before performing arithmetic.
function double(x) {
if (typeof x !== "number") throw new TypeError("Expected a number");
return x * 2;
}
console.log(double(5)); // 10
// double("hi"); // TypeError: Expected a numberinstanceof for class checking
Shows that instanceof checks the entire prototype chain, so a Dog is also an instance of Animal.
class Animal {}
class Dog extends Animal {}
const d = new Dog();
console.log(d instanceof Dog); // true
console.log(d instanceof Animal); // true – checks prototype chaininstanceof for error branching
Uses instanceof to distinguish a NetworkError from other errors and decide whether to retry.
class NetworkError extends Error {}
try {
throw new NetworkError("timeout");
} catch (e) {
if (e instanceof NetworkError) console.log("Retry:", e.message);
else throw e;
}
Discussion