To get the constructor or class name of an object in JavaScript, check value.constructor?.name after guarding against null and undefined (since primitives like null and undefined have no .constructor property), and handle edge cases such as null-prototype objects (Object.create(null)), minified/anonymized classes, or custom Symbol.toStringTag descriptors rather than assuming obj.constructor.name always returns a descriptive, non-empty string.
1. Safe Constructor / Class Name Lookup with Null and Prototype Guards
Validate that value is not null or undefined, safely inspect value.constructor?.name, and fall back cleanly when an object has a null prototype or no named constructor:
// Safely resolve the constructor or class name of any JavaScript value
function getTypeName(value) {
if (value === null) {
return "Null";
}
if (value === undefined) {
return "Undefined";
}
try {
const proto = typeof Object.getPrototypeOf === "function" ? Object.getPrototypeOf(value) : null;
if (proto === null) {
return "NullPrototypeObject";
}
const ctor = value.constructor;
if (typeof ctor === "function" && typeof ctor.name === "string" && ctor.name.trim().length > 0) {
return ctor.name;
}
const tag = value[Symbol.toStringTag];
if (typeof tag === "string" && tag.trim().length > 0) {
return tag.trim();
}
return typeof value;
} catch (error) {
throw new Error(`Failed to resolve constructor/class name: ${error.message}`);
}
}
// Example usage:
try {
class OrderService {}
const order = new OrderService();
const dict = Object.create(null);
console.log(getTypeName(order)); // "OrderService"
console.log(getTypeName([1, 2])); // "Array"
console.log(getTypeName(new Map())); // "Map"
console.log(getTypeName(dict)); // "NullPrototypeObject"
console.log(getTypeName(null)); // "Null"
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
- Always guard
nullandundefinedfirst: Accessingnull.constructororundefined.constructorthrows aTypeError. - Check
Object.getPrototypeOf(value) === nullbefore reading.constructor: Objects created withObject.create(null)inherit fromnull, notObject.prototype, sodict.constructorisundefined.
2. Production Pitfalls: Minification, Anonymous Classes, and Overridden .constructor
In real-world builds and complex object graphs, relying blindly on obj.constructor.name can surprise you:
// Inspect class vs. prototype chain without relying solely on mutable `.constructor`
function inspectPrototypeChain(instance) {
if (instance === null || (typeof instance !== "object" && typeof instance !== "function")) {
throw new TypeError("Expected instance to be a non-null object or function.");
}
try {
const chain = [];
let currentProto = Object.getPrototypeOf(instance);
while (currentProto !== null) {
const ctorName =
currentProto.constructor && typeof currentProto.constructor.name === "string"
? currentProto.constructor.name
: "<anonymous>";
chain.push(ctorName);
currentProto = Object.getPrototypeOf(currentProto);
}
return chain;
} catch (error) {
throw new Error(`Failed inspecting prototype chain: ${error.message}`);
}
}
// Example usage:
try {
class BaseWorker {}
class SyncWorker extends BaseWorker {}
console.log(inspectPrototypeChain(new SyncWorker())); // ["SyncWorker", "BaseWorker", "Object"]
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
- Bundlers/minifiers can mangle or strip class names: Aggressive minification or anonymous class expressions (
const C = class {}) can shorten or emptyctor.name. - Prefer
instanceofor explicit type tags/discriminators for runtime type checks: Never useobj.constructor.name === "MyClass"as a security or protocol check—useinstanceofor an explicitkind/typefield.
3. Cross-Realm / vm / iframe Nuances and Explicit Class Metadata
When objects cross execution contexts (such as an <iframe> in the browser or a node:vm context in Node.js) or when you want stable names independent of minification, keep cross-realm behavior in mind:
- Cross-realm
instanceofcan behave differently from constructor names: AnArrayor custom class instance created inside another realm has its own realm’s constructor function, even though.constructor.namestill reports the class name string. - Attach explicit metadata (
static readonly kind = ...or aMapregistry) when names must survive minification: Relying on runtimeFunction.prototype.nameis helpful for logging/diagnostics, not guaranteed invariant identifiers. - Avoid mutating
Object.prototype: Modifying shared prototypes can pollute constructor lookups across unrelated objects and libraries.