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
# using npm npm install --save is-plain # using yarn yarn add is-plain
Usage
; ;//=> true ;//=> true ;//=> true {};//=> false ;//=> false ;//=> false ;//=> false
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
// an object without a prototypeconst value = Object;
is value a plain object? |
||
---|---|---|
is-plain (this package) |
true |
|
is-plain-obj |
true |
|
⚠️ | is-plain-object |
false |
lodash.isplainobject |
true |
Case 2
// an object with an empty prototypeconst value = Object;
is value a plain object? |
||
---|---|---|
is-plain (this package) |
true |
|
⚠️ | is-plain-obj |
false |
is-plain-object |
true |
|
⚠️ | lodash.isplainobject |
false |
Case 3
// an object with a prototype whose constructor is Objectconst value = Object
is value a plain object? |
||
---|---|---|
is-plain (this package) |
true |
|
⚠️ | is-plain-obj |
false |
is-plain-object |
true |
|
lodash.isplainobject |
true |
Case 4
// an object literal with own property 'constructor'const value =
is value a plain object? |
||
---|---|---|
is-plain (this package) |
true |
|
is-plain-obj |
true |
|
⚠️ | is-plain-object |
false |
lodash.isplainobject |
true |
Case 5
// an object literal with a '__proto__' property as an objectconst 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
// an instance of a prototype whose constructor is Object {}ObjectConstructorprototypeconstructor = Object;const value = ;
is value a plain object? |
||
---|---|---|
is-plain (this package) |
true |
|
⚠️ | is-plain-obj |
false |
is-plain-object |
true |
|
lodash.isplainobject |
true |
License
MIT