check variable is object

I find myself writing this helper function way too often:

const isObject = obj => Object.prototype.toString.call(obj) === "[object Object]";
  • works on regular objects
  • works on null prototype objects
  • rejects arrays
  • rejects null

A Object.isObject function would be very much welcome by me, and I think such a proposal would be quite a trivial one. Anyone willing to champion it?

You can use this utility function:

const isObject = value => value === Object(value)

Arrays will evaluate to true because they are objects.

Object.prototype.toString is no longer reliable after ES6, because of Symbol.toStringTag, so that function is incorrect. Indeed the most reliable way to tell if something is an object (ie, not a primitive) is Object(x) === x.

1 Like