Explain Codes LogoExplain Codes Logo

Get the name of an object's type

javascript
object-type
javascript-objects
type-checking
Anton ShumikhinbyAnton Shumikhin·Jan 8, 2025
TLDR

Just need a quick and dirty solution? This function will get you the type name of any object:

const typeName = (obj) => obj.constructor.name; // Examples: console.log(typeName({})); // "Object", as solid as a rock console.log(typeName([])); // "Array", this one holds it together console.log(typeName(new Date())); // "Date", haven't lost track of time, have we?

Grasping the Essence - Object Type Identification

The Deal with constructor.name

The constructor.name property provides the name of the function that constructed the object instance. However, this property can be manipulated or even absent, leading to potential misunderstanding.

Rolling Reliable with Object.prototype.toString.call(obj)

The method Object.prototype.toString.call(obj) provides a more dependable way to get an object type. It shows a more precise and standardized output pertaining to the object type:

console.log(Object.prototype.toString.call([])); // "[object Array]", array-n't you surprised? console.log(Object.prototype.toString.call(new Date())); // "[object Date]", always up-to-date!

Traps of typeof

The typeof operator is useful but limited. It does not differentiate between object types like an array, a plain object, or null.

console.log(typeof []); // "object", array of confusion console.log(typeof {}); // "object", the plain truth console.log(typeof null); // "object", null to see here

It's better to use typeof when dealing with JavaScript primitives or when a broad evaluation is sufficient.

All about instanceof

The instanceof operator checks whether an object is an instance of a certain class. This is particularly useful when you are dealing with custom objects and want to verify their inheritance:

console.log([] instanceof Array); // true, genuine as a pearl console.log(new Date() instanceof Date); // true, no fake news here

Remember, instanceof only works for objects, not for primitive values.

Real-World Scenarios and Solutions

Is it an Array, or…?

If you are checking whether an object is an Array, Array.isArray(obj) is your friend:

console.log(Array.isArray([])); // true, it has length but doesn't go the distance

Function Finder

If you need to differentiate functions from other objects, typeof with a function-specific check works great:

const isFunction = (obj) => typeof obj === 'function'; console.log(isFunction(() => {})); // true, function-alities included

Distinguishing Native Types

When dealing with certain built-in types like RegExp or Date, be sure to use precise checks:

const isDate = (obj) => Object.prototype.toString.call(obj) === '[object Date]'; console.log(isDate(new Date())); // true, no need for a time machine