Detect JavaScript Types with Object.prototype.toString.call
· One min read
typeof works well for primitives, but arrays, plain objects, and null require more specific checks. Object.prototype.toString.call exposes a useful built-in type tag.
const objectToString = Object.prototype.toString;
objectToString.call([123]); // [object Array]
objectToString.call("123"); // [object String]
objectToString.call({a: 1}); // [object Object]
objectToString.call(/123/); // [object RegExp]
objectToString.call(123); // [object Number]
objectToString.call(undefined); // [object Undefined]
objectToString.call(null); // [object Null]
A reusable helper:
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
Use typeof for strings, numbers, booleans, symbols, bigints, undefined, and functions. Use Array.isArray(value) when only arrays matter. instanceof is useful for custom classes but can fail across iframe or realm boundaries.
Objects may customize their tag with Symbol.toStringTag, so this technique is not a security boundary. Validate required properties and data provenance when processing untrusted input.