guest271314 guest271314 - 2 months ago 17
Javascript Question

Why is there not a built-in method in JavaScript to check if an object is a plain object?

Given the developments of

since the languages' inception, why is there not a built in method that checks if an object is a plain object?

Or does the method in fact exist?


There doesn't exist any explicit direct way to check if a value is an object, i.e. belongs to Object type, but there are some foolproof ways to do it. I wrote a list in another answer, the most succinct seems

function isObject(value) {
  return Object(value) === value;

A feature like this has been requested multiple times on esdiscuss. For example,

In fact, Object.isObject was proposed as strawman, and it appeared in an ES6 early draft.

Object.isObject strawman was eventually rejected and removed from ES6 draft.

More recently,

Now there is the is{Type} Methods stage 0 proposal which includes Object.isObject among lots of various other checks.

So there is still hope and eventually we may have something like this.

The above is for testing objects in general. If you don't want that you should define what "plain object" means for you.

For example, you can test the constructor property. But any object can customize it.

You can use Object.prototype.toString to get the legacy ES5 [[Class]]. But any object can customize that via Symbol.toStringTag.

You can check the value returned by [[GetPrototypeOf]]. But even exotic objects might allow their prototype to be changed to whatever arbitrary object or null. And Proxy objects even have full control over that internal method.

So most probably you won't be able to rely on these tests. And adding something to the standard may be hard because different people may want different things.

What I would like is some way to check if an object is an ordinary one. That is, it has the default behaviour for the essential internal methods that must be supported by all objects.

Once you know that an object is ordinary, you can rely on things like [[GetPrototypeOf]] to customize the test to your tastes.