is-plain
📖 Table of Contents
Tests if a value is a plain object. That is:
- an object created using
new Object()
- or, an object without a prototype
Object.create(null)
- or, an object created using the literal notation
{}
Installation
npm install --save is-plain
yarn add is-plain
Usage
import isPlain from 'is-plain';
isPlain({ foo: 'bar' });
isPlain(Object.create(null));
isPlain(new Object());
class Foo {}
isPlain(new Foo());
isPlain([1, 2, 3]);
isPlain(null);
isPlain(Promise.resolve());
Comparison with Other Libraries
There are already similar libraries available to test if a value is a plain object. Some of these libraries are very widely adopted. To name a few:
So, why need is-plain
when other solutions already exist?
Small Package Size
is-plain
is only 140 bytes minzipped.
The following is a size comparison between is-plain
and other popular libraries ranked by their minified size:
Edge Cases Other Libraries Missed
While is-plain
is very comparable to is-plain-obj
in both size and logic (is-plain
being smaller by 3 bytes), the size wasn't the the only motive. Most importantly, what I wanted to address is some of the edge cases the other libraries are missing.
The following are some of the cases that causes inconsistent, arguably incorrect, results when one of the other three libraries is used (note that in all of the following cases, is-plain
considers these objects to be plain objects).
Case 1
const value = Object.create(null);
| | is value a plain object? |
---|
| is-plain (this package) | true |
| is-plain-obj | true |
⚠️ | is-plain-object | false |
| lodash.isplainobject | true |
Case 2
const value = Object.create({});
| | is value a plain object? |
---|
| is-plain (this package) | true |
⚠️ | is-plain-obj | false |
| is-plain-object | true |
⚠️ | lodash.isplainobject | false |
Case 3
const value = Object.create({ constructor: Object });
| | is value a plain object? |
---|
| is-plain (this package) | true |
⚠️ | is-plain-obj | false |
| is-plain-object | true |
| lodash.isplainobject | true |
Case 4
const value = {
constructor: Foo,
};
| | is value a plain object? |
---|
| is-plain (this package) | true |
| is-plain-obj | true |
⚠️ | is-plain-object | false |
| lodash.isplainobject | true |
Case 5
const value = {
__proto__: {},
};
| | is value a plain object? |
---|
| is-plain (this package) | true |
⚠️ | is-plain-obj | false |
| is-plain-object | true |
⚠️ | lodash.isplainobject | false |
Case 6
function ObjectConstructor() {}
ObjectConstructor.prototype.constructor = Object;
const value = new ObjectConstructor();
| | is value a plain object? |
---|
| is-plain (this package) | true |
⚠️ | is-plain-obj | false |
| is-plain-object | true |
| lodash.isplainobject | true |
License
MIT