Sub topic 18
Checking Types Reliably
This chapter assumes you know what typeof returns for each type, including the typeof null quirk. It also assumes you know that primitives such as strings get methods through temporary wrapper objects. Here the goal is practical: for each kind of value you might need to detect, which check gives the right answer every time, and where does each check break?
Why typeof Is Not Enough
typeof is a good first check, and it can never throw on a value. It still has three gaps:
typeof nullis"object", so a baretypeof x === "object"check letsnullthrough.- Arrays, dates, maps, regular expressions, and plain objects all report
"object". - Wrapper objects such as
new String("a")report"object", while the primitive"a"reports"string".
typeof is accurate for the primitive types and for functions, so use it there. For anything that reports "object", you need a second check.
typeof undeclaredName; // "undefined": no ReferenceError for undeclared names
typeof class Point {}; // "function": classes are functions
typeof new String("a"); // "object": a wrapper, not a primitive
typeof async () => {}; // "function"Checking for null and undefined
Compare directly. Both values are unique, so strict equality is exact:
function describe(value) {
if (value === null) return "null";
if (value === undefined) return "undefined";
if (value == null) return "unreachable"; // == null matches both at once
return "something";
}
describe(null); // "null"
describe(undefined); // "undefined"
describe(0); // "something"value == null is the one loose comparison many style guides allow. It is true only for null and undefined, so it reads as "is this missing?" To check for "a real object", combine the two tests: typeof value === "object" && value !== null.
Checking for Arrays
Use Array.isArray. It checks an internal property of the value, so it cannot be fooled by look-alike objects, and it works across realms. A realm is a separate global environment, such as an iframe or a Node.js vm context, with its own copy of Array.
const vm = require("node:vm");
const foreignArray = vm.runInNewContext("[1, 2, 3]");
foreignArray instanceof Array; // false: built by a different Array constructor
Array.isArray(foreignArray); // true
Array.isArray({ length: 0 }); // false: array-like is not an array
Array.isArray(new Array(3)); // trueRun this in Node.js. In a browser you get the same result with an array that comes from an iframe's contentWindow.
instanceof and Its Failure Modes
value instanceof C walks the prototype chain of value and looks for C.prototype. It does not inspect what the value really is, and that causes several failures:
| Situation | Result | Why |
|---|---|---|
| Object from another realm | `false` | That realm has a different `C.prototype` |
| `Object.create(null)` | `false` for `instanceof Object` | Its prototype chain is empty |
| Primitive such as `"a" instanceof String` | `false` | Primitives have no prototype chain to walk |
| `Object.setPrototypeOf(obj, Date.prototype)` | `true` for `instanceof Date` | Only the chain is checked, so it can be faked |
| Class with `static [Symbol.hasInstance]` | Whatever the method returns | The class overrides the check |
instanceof is still the right tool for your own classes inside one realm, for example err instanceof ValidationError. For built-in types, prefer the dedicated checks.
Object.prototype.toString as a Tag Reader
Calling Object.prototype.toString on a value returns "[object Tag]". Built-ins have specific tags, and null and undefined get their own tags:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
tag(null); // "Null"
tag(undefined); // "Undefined"
tag([]); // "Array"
tag(new Date()); // "Date"
tag(/x/); // "RegExp"
tag(new Map()); // "Map"
tag(Promise.resolve()); // "Promise"
tag("a"); // "String"
tag(new String("a")); // "String": wrapper and primitive look the same
tag(new (class Point {})()); // "Object"Since ES2015, any object can set its tag through Symbol.toStringTag, so a tag is a hint rather than proof:
const fake = { [Symbol.toStringTag]: "Array" };
Object.prototype.toString.call(fake); // "[object Array]"
Array.isArray(fake); // falseMany built-ins, including Map, Promise, and Symbol, get their tags from Symbol.toStringTag. Older ones, such as Array, Date, and RegExp, get their tags from internal slots, but an own Symbol.toStringTag property still takes precedence.
Numbers: Picking the Right Predicate
typeof x === "number" is true for NaN and Infinity. Decide what you mean by "number" and pick the matching predicate:
Number.isNaN(NaN); // true
Number.isNaN("abc"); // false: no coercion
Number.isFinite(42); // true
Number.isFinite("42"); // false: global isFinite("42") is true
Number.isFinite(Infinity); // false
Number.isInteger(5.0); // true
Number.isInteger(5.5); // false
Number.isSafeInteger(2 ** 53); // false
Number.isSafeInteger(2 ** 53 - 1); // true
typeof 10n === "bigint"; // true: BigInt needs its own checkThe Number.* versions never coerce their argument. The global isNaN and isFinite convert it to a number first, and that is how isNaN("abc") ends up true.
Detecting Wrapper Objects and Plain Objects
To tell a primitive string from a String wrapper, compare typeof with the tag. To find a plain object, meaning one created by {} or Object.create(null), check its prototype directly:
function isWrapper(v) {
return typeof v === "object" && v !== null &&
["String", "Number", "Boolean", "BigInt", "Symbol"]
.includes(Object.prototype.toString.call(v).slice(8, -1));
}
function isPlainObject(v) {
if (typeof v !== "object" || v === null) return false;
const proto = Object.getPrototypeOf(v);
return proto === Object.prototype || proto === null;
}
isWrapper(new Number(1)); // true
isWrapper(1); // false
isPlainObject({}); // true
isPlainObject(Object.create(null)); // true
isPlainObject([]); // false
isPlainObject(new Date()); // falseisPlainObject compares against the current realm's Object.prototype, so it returns false for a plain object from another realm. If your values cross realms, check that Object.getPrototypeOf(proto) === null instead.
Choosing a Check
The flowchart condenses into one helper:
function typeOf(value) {
if (value === null) return "null";
const t = typeof value;
if (t !== "object") return t;
if (Array.isArray(value)) return "array";
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
typeOf(null); // "null"
typeOf([]); // "array"
typeOf(new Date()); // "date"
typeOf(new Map()); // "map"
typeOf({}); // "object"
typeOf(() => {}); // "function"
typeOf(new String("a")); // "string": the wrapper is reported by its tag| Want to detect | Reliable check | Avoid |
|---|---|---|
| null | `v === null` | `typeof v === "object"` |
| null or undefined | `v == null` | `!v` (also catches 0 and "") |
| Array | `Array.isArray(v)` | `instanceof Array`, `v.length` |
| Real number | `Number.isFinite(v)` | `typeof v === "number"` alone |
| NaN | `Number.isNaN(v)` | `v === NaN`, global `isNaN` |
| Function | `typeof v === "function"` | toString tag (async functions are "AsyncFunction") |
| Date, Map, RegExp | toString tag or `instanceof` in one realm | `typeof` |
| Own class | `instanceof` | toString tag (usually "Object") |
Exercise
A function receives value from a sandboxed vm context and runs if (value instanceof Array && typeof value === "object"). For the input vm.runInNewContext("[]") the branch never runs. Explain why, and give a corrected condition.
Show answer
The array was created by the sandbox's own Array constructor, so its prototype chain contains the sandbox's Array.prototype rather than the main realm's, and instanceof Array is false. The typeof part is redundant, since every array reports "object". Use Array.isArray(value), which checks the internal array property and works across realms.
Exercise
What does typeOf (defined above) return for Object.create(null), new Number(5), NaN, and { [Symbol.toStringTag]: "Date" }? Which of these results could mislead a caller?
Show answer
"object", "number", "number", and "date". The new Number(5) result hides that the value is a wrapper object, which is truthy even when it wraps 0. The NaN result says "number", although NaN is not a usable number. The spoofed object reports "date" but has no Date methods. Callers that need certainty should use typeof, Number.isNaN, or instanceof Date together with the tag.
Exercise
Write isNonEmptyString(v) that returns true only for primitive strings containing at least one non-whitespace character, and false for new String("hi").
Show answer
const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0; The typeof test rejects wrappers, because they report "object", and it rejects every non-string. trim() removes whitespace before the length check.