Sub topic 17
Inspecting Values with typeof, instanceof, and in
This chapter assumes you already know JavaScript's primitive types and how objects and prototypes relate. It also assumes you understand reference equality from the earlier chapter. Three operators let you ask questions about a value at runtime:
typeofasks "what kind of primitive or callable is this?"instanceofasks "is this constructor's prototype somewhere in this object's prototype chain?"inasks "does this object have this property, either its own or inherited?"
All three return a string or a boolean and never throw for ordinary use. Each one answers a narrower question than its name suggests, and most bugs with these operators come from expecting more than that.
typeof: A Type Tag as a String
typeof is a unary operator. It returns one of eight strings.
| Value | `typeof` result |
|---|---|
| `undefined` | `'undefined'` |
| `null` | `'object'` |
| `true` / `false` | `'boolean'` |
| `42`, `NaN`, `Infinity` | `'number'` |
| `10n` | `'bigint'` |
| `'text'` | `'string'` |
| `Symbol()` | `'symbol'` |
| any function or class | `'function'` |
| any other object | `'object'` |
console.log(typeof 42); // 'number'
console.log(typeof NaN); // 'number'
console.log(typeof 10n); // 'bigint'
console.log(typeof Symbol('id')); // 'symbol'
console.log(typeof undefined); // 'undefined'
console.log(typeof null); // 'object'
console.log(typeof function () {}); // 'function'
console.log(typeof class {}); // 'function'
console.log(typeof []); // 'object'
console.log(typeof new Date()); // 'object'
console.log(typeof new String('a')); // 'object' (a wrapper object, not a primitive)The null quirk
typeof null === 'object' is a bug from the first JavaScript engine, kept so that existing code would not break. To check for a real object, rule out null explicitly:
function isObjectLike(value) {
return typeof value === 'object' && value !== null;
}
console.log(isObjectLike({})); // true
console.log(isObjectLike([])); // true
console.log(isObjectLike(null)); // falseIf you also want to accept functions, add || typeof value === 'function'.
typeof on undeclared names and the TDZ
typeof is the only operator that can be applied to a name that was never declared without throwing. This matters for feature detection, for example checking typeof window in code that might run in Node.js. Variables declared with let, const, or class are different: before their declaration line runs they sit in the temporal dead zone (TDZ), and typeof on them does throw.
console.log(typeof neverDeclared); // 'undefined', no error
try {
console.log(typeof notYet);
let notYet = 1;
} catch (e) {
console.log(e instanceof ReferenceError); // true: notYet is in its TDZ
}instanceof: Walking the Prototype Chain
obj instanceof C takes C.prototype and walks up from obj through Object.getPrototypeOf until it finds that object (true) or reaches null (false). It does not look at how the object was created or what properties it has.
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // true
console.log(rex instanceof Object); // true
console.log([] instanceof Array); // true
console.log([] instanceof Object); // trueWhere instanceof gives surprising answers
The algorithm is simple, so the surprises all come from the chain itself.
// Primitives have no prototype chain to walk
console.log('abc' instanceof String); // false
console.log(new String('abc') instanceof String); // true
// Objects created without a prototype
const bare = Object.create(null);
console.log(bare instanceof Object); // false
// The chain can be changed after creation
const fake = {};
Object.setPrototypeOf(fake, Array.prototype);
console.log(fake instanceof Array); // true
console.log(Array.isArray(fake)); // false: not a real array
// A class can override the check
class Even {
static [Symbol.hasInstance](n) {
return n % 2 === 0;
}
}
console.log(2 instanceof Even); // true
console.log(3 instanceof Even); // falseThe right-hand side must be callable. {} instanceof {} throws a TypeError.
Realms: why Array.isArray exists
Each iframe, worker, or Node.js vm context is a separate realm, and each realm has its own Array constructor and Array.prototype. An array created in an iframe is not instanceof Array in the parent page, because its chain leads to a different Array.prototype. Array.isArray checks the internal array type instead, so it works across realms. When a value might cross a realm boundary (for example postMessage results or values from a test sandbox), prefer brand checks like Array.isArray over instanceof.
in: Does the Property Exist?
key in obj returns true if the property exists on the object or anywhere on its prototype chain, even when its value is undefined. That last point is what makes in different from checking obj.key !== undefined.
const config = { debug: undefined };
console.log(config.debug !== undefined); // false: looks missing
console.log('debug' in config); // true: it exists
console.log('toString' in config); // true: inherited from Object.prototype
console.log(Object.hasOwn(config, 'toString')); // false: not an own property
console.log(Object.hasOwn(config, 'debug')); // trueUse Object.hasOwn when inherited properties should not count, such as when an object is used as a dictionary of user-supplied keys.
Arrays and holes
For arrays, in checks indices as property keys, which shows the difference between a missing slot and a slot holding undefined.
const sparse = [1, , 3];
const filled = [1, undefined, 3];
console.log(1 in sparse); // false: a hole
console.log(1 in filled); // true
console.log('length' in []); // true
console.log(2 in ['a', 'b']); // false: in tests indices, not valuesA common mistake is writing 'b' in ['a', 'b'] to test membership. That returns false. Use includes for values.
Right-hand side must be an object
in throws a TypeError if the right operand is a primitive.
try {
console.log('length' in 'abc');
} catch (e) {
console.log(e instanceof TypeError); // true
}Private brand checks
Inside a class body, #field in obj tests whether obj was constructed by that class. Unlike instanceof, you cannot fake it with setPrototypeOf.
class Point {
#x = 0;
static isPoint(obj) {
return #x in obj;
}
}
console.log(Point.isPoint(new Point())); // true
console.log(Point.isPoint(Object.create(Point.prototype))); // false
console.log(Object.create(Point.prototype) instanceof Point); // truePrecedence Gotcha with Negation
instanceof and in share precedence with < and >, which is lower than !. Negating without parentheses negates the left operand first.
const obj = { x: 1 };
console.log(!'x' in obj); // false: evaluates (false) in obj, i.e. 'false' in obj
console.log(!('x' in obj)); // false: correct negation, x exists
console.log(!('y' in obj)); // true
console.log(!([] instanceof Array)); // falseAlways wrap the whole test in parentheses before negating.
Choosing the Right Check
| Question | Use |
|---|---|
| Is it a primitive of type X? | `typeof v === 'X'` |
| Is it a non-null object? | `typeof v === 'object' && v !== null` |
| Is it callable? | `typeof v === 'function'` |
| Is it an array? | `Array.isArray(v)` |
| Was it built from this class (same realm)? | `v instanceof C` |
| Was it built from this class, unforgeably? | `#field in v` inside the class |
| Does the property exist, inherited or not? | `key in obj` |
| Is the property its own? | `Object.hasOwn(obj, key)` |
Exercise
What does each line print, and why? (1) typeof typeof 1 (2) null instanceof Object (3) 'constructor' in {} (4) 0 in [undefined]
Show answer
(1) 'string', because typeof 1 is the string 'number', and typeof of a string is 'string'. (2) false, because null has no prototype chain. (3) true, because constructor is inherited from Object.prototype. (4) true, because index 0 exists even though its value is undefined.
Exercise
Write a function isPlainObject(v) that returns true for {} and Object.create(null) but false for null, arrays, and functions.
Show answer
function isPlainObject(v) { if (typeof v !== 'object' || v === null) return false; const proto = Object.getPrototypeOf(v); return proto === null || proto === Object.prototype; } typeof rules out functions and primitives, the null check handles the typeof null quirk, and the prototype check excludes arrays and class instances.
Exercise
A teammate writes if (!key in cache) to detect a missing key, and the branch never runs. Explain the bug and fix it.
Show answer
! binds tighter than in, so !key becomes a boolean and the test checks whether the property 'true' or 'false' exists in cache, which is almost always false. Fix it with if (!(key in cache)), or with if (!Object.hasOwn(cache, key)) if inherited keys should not count.