Search code examples
javascriptobjectprototype

How can I check whether an object is a "plain" object?


I'm not exactly sure what the correct terminology is for this question, so I will do my best to explain.

Lots of things in JavaScript are objects, like arrays, and class instantiations.

typeof {"a": 3}     // "object"
typeof (new foo())  // "object"
tyepof [1, 2, 3]    // "object"

If you have a function that accepts an object, how do you check if the object is a "plain" object like the top one, e.g. not an instantiation of a class, an error, etc, but just a normal object?

I've tried checking the prototype, but I haven't been able to determine consistently whether an object is an instantiation of something or an array or something like that vs. just a normal object.

Any help would be greatly appreciated.


Solution

  • I don't know if this is a comprehensive solution, but you could check against the constructor property:

    function foo() {}
    class Bar {}
    
    console.log(
      {}.constructor === Object, // this is the "plain" object
      [].constructor === Object,
      ''.constructor === Object,
      (new foo()).constructor === Object,
      (new Bar()).constructor === Object,
      (new Map()).constructor === Object,
      (new Set()).constructor === Object,
      (new WeakMap()).constructor === Object,
      (new WeakSet()).constructor === Object,
      (new Error()).constructor === Object,
    );

    (Edit: I cannot think of any other kinds of objects)