Detecting plain objects

When we say plain objects, we are typically referring to those that are constructed as either Object literals or via the Object constructor:

const plainObject = {
name: 'Pikachu',
species: 'Pokémon'
};

const anotherPlainObject = new Object();
anotherPlainObject.name = 'Pikachu';
anotherPlainObject.species = 'Pokémon';

This is in contrast to other objects, such as those provided natively by the language (for example, arrays) and those that we construct ourselves via instantiating constructors (for example, new Pokemon()):

function Pokemon() {}
new Pokemon(); // => A non-plain object

The simplest way to detect a plain object is to inquire as to its [[Prototype]]. If it has a [[Prototype]] equal to Object.prototype, then we can say it is plain:

function isPlainObject(object) {
return Object.getPrototypeOf(object) === Object.prototype;
}

isPlainObject([]); // => false
isPlainObject(123); // => false
isPlainObject(new String); // => false
isPlainObject(new Pokemon()); // => false

isPlainObject(new Object()); // => true
isPlainObject({}); // => true

Why would we need to know whether a value is a plain object? It may, for example, be useful to discern plain from non-plain objects when creating an interface or function that accepts configuration objects in addition to more complex object types.

In most situations, we will need to detect a plain object explicitly. Instead, we should rely only on the interface or data that it provides us. If a user of our abstraction wishes to pass us a non-plain object but it still has the properties that we require, then who are we to complain?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.26.246