JS: Determine the type of an object

By Xah Lee. Date: . Last updated: .

How to find out if a object is function, array, date, regex, etc?

Check if object is array

Check if object is function

Using Object.prototype.toString

const xx = new Date();

console.assert(
 Reflect.apply(
  Object.prototype.toString,
  xx,
  [],
 ) ===
  "[object Date]",
);

No generic reliable way

note, there is no generic reliable way to find the type of a object.

Array.isArray is for checking array.

typeof operator can be used for checking if it is a function. but not distinguish from normal function vs async function

using Object.prototype.toString is not reliable because anyone can add a Symbol.toStringTag property with arbitrary value.

instanceof and .constructor are both not reliable.