All topics
Fundamentalsbeginner

typeof and instanceof Operators

Two different tools for checking a value's type at runtime — one for primitives, one for constructor-based checks on objects.

Determining what kind of value you're holding at runtime is a routine task in JavaScript because the language is dynamically typed, and typeof and instanceof are the two primary tools for it, each suited to different situations. Interviewers ask about these because their edge cases reveal how well you understand JS's type system quirks.

`typeof` is like glancing at a package's shipping label to see if it says 'liquid,' 'solid,' or 'fragile' — a coarse category. `instanceof` is like checking a product's manufacturer stamp to confirm it specifically came from a particular factory (constructor) somewhere down its supply chain (prototype chain).

Key Concepts

1
typeof returns a string describing a value's primitive type: 'string', 'number', 'boolean', 'undefined', 'symbol', 'bigint', or 'function' for callable objects. Its most famous quirk is typeof null === 'object', a bug from the very first JavaScript implementation that has been kept for backwards compatibility ever since. typeof treats all non-function objects — including arrays, dates, and plain objects — as 'object', so it cannot distinguish between them.
typeof'string''number''boolean''undefined'
2
instanceof checks whether an object's prototype chain includes the prototype property of a given constructor, making it useful for distinguishing Array from Date from a custom class instance. [] instanceof Array is true, and new Date() instanceof Date is true, but instanceof fails across different execution contexts (like iframes) because each context has its own separate constructor identity, so an array from one iframe is not instanceof the Array constructor in another.
instanceofprototypeArrayDate[] instanceof Array
3
For a more reliable way to distinguish object types like arrays, Array.isArray() is preferred over instanceof Array. And for a precise tag across many built-in types, Object.prototype.toString.call(value) (e.g., returning '[object Array]' or '[object Null]') is the most robust, if verbose, technique — often brought up as the 'advanced' answer in interviews.
Array.isArray()instanceof ArrayObject.prototype.toString.call(value)'[object Array]''[object Null]'