Check if a value is a plain object in JavaScript
Advanced · 3 min read
A plain object is the simple kind of object you write with curly braces, { plate: 'LAG-441-XA' }, or get back from JSON.parse. It is just a bag of keys and values. A class instance, an array or a date is also an object, but it is more than a bag of data.
Telling them apart matters when you merge settings, copy data or turn it into JSON. Code that treats a class instance like a plain bag usually breaks it. In this tutorial you will write isPlainObject. You should know what an object is and have seen a class. The idea it needs, the prototype, is explained from zero.
Prototypes, in plain words
Every object has a hidden link to another object, called its prototype. When you read a property the object doesn't have, JavaScript looks it up on the prototype instead.
That is why an empty-looking object still has a toString method. It isn't stored on the object. It comes from Object.prototype, the prototype every {} gets:
const literal = { plate: 'LAG-441-XA' };
console.log(Object.getPrototypeOf(literal) === Object.prototype); // true
console.log(typeof literal.toString); // function
console.log(Object.hasOwn(literal, 'toString')); // false
Object.getPrototypeOf reads that hidden link. Object.hasOwn asks whether the object itself holds the key. It doesn't, so toString must come from the prototype.
Class instances have a different prototype
An object made with new from a class gets the class's prototype, where the class's methods live. That prototype then links on to Object.prototype:
class Bus {
constructor(plate) { this.plate = plate; }
}
const instance = new Bus('ENU-318-PH');
console.log(Object.getPrototypeOf(instance) === Bus.prototype); // true
console.log(Object.getPrototypeOf(instance) === Object.prototype); // false
So the prototype is what tells a plain object apart from a class instance.
Here is the exercise. Have a go on your own if you like, or read on and we will build it together.
7 Is it a plain object?
hardDistinguish a plain {} — the kind that comes out of JSON.parse — from a class instance, an array, a date, or anything else that happens to be an object.
Stuck? Three hints, smallest first
- 1. Check the prototype: a plain object’s is exactly
Object.prototype. - 2.
Object.create(null)has no prototype and is arguably the plainest object of all. - 3. A class instance has its own prototype in between, so the direct comparison fails for it.
Step 1: rule out the other kinds
Start with the tag check. Object.prototype.toString.call(v) describes any value as a string like '[object Array]', and .slice(8, -1) keeps the middle word:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
console.log(tag([])); // Array
console.log(tag(new Date())); // Date
console.log(tag(new Map())); // Map
console.log(tag(null)); // Null
console.log(tag({})); // Object
Anything whose tag isn't 'Object' is definitely not plain. That clears out arrays, dates, maps, null and functions in one line.
Step 2: the wrong turn
It is tempting to stop there and call every 'Object' plain. But look at a class instance:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
class Bus {
constructor(plate) { this.plate = plate; }
}
console.log(tag(new Bus('ENU-318-PH'))); // Object
The tag says 'Object' too. On its own, the tag can't spot class instances.
Step 3: check the prototype
After the tag check, read the prototype and compare it with Object.prototype:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
function isPlainObject(v) {
if (tag(v) !== 'Object') return false;
return Object.getPrototypeOf(v) === Object.prototype;
}
class Bus {
constructor(plate) { this.plate = plate; }
}
console.log(isPlainObject({ plate: 'LAG-441-XA' })); // true
console.log(isPlainObject(JSON.parse('{"plate":"KAN-905-BD"}'))); // true
console.log(isPlainObject(new Bus('ENU-318-PH'))); // false
console.log(isPlainObject([])); // false
The object literal and the JSON.parse result both link straight to Object.prototype. The bus links to Bus.prototype first, so it fails.
Step 4: objects with no prototype
Object.create(null) makes an object whose prototype is null. It inherits nothing at all, not even toString:
const bare = Object.create(null);
bare.plate = 'ABJ-772-KM';
console.log(Object.getPrototypeOf(bare)); // null
console.log(typeof bare.toString); // undefined
console.log(bare.plate); // ABJ-772-KM
This is arguably the plainest object of all, so let it through too:
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
function isPlainObject(v) {
if (tag(v) !== 'Object') return false;
const proto = Object.getPrototypeOf(v);
return proto === Object.prototype || proto === null;
}
console.log(isPlainObject(Object.create(null))); // true
console.log(isPlainObject({ a: { b: 1 } })); // true
console.log(isPlainObject(() => {})); // false
Prototype-less objects are a good choice for a lookup table built from keys a user typed. On a normal {}, a key like 'toString' already "exists" because it is inherited:
console.log('toString' in {}); // true
console.log('toString' in Object.create(null)); // false
Why it matters
Here is what happens when you copy a class instance as if it were a plain bag:
class Bus {
constructor(plate) { this.plate = plate; }
describe() { return 'Bus ' + this.plate; }
}
const copy = { ...new Bus('ENU-318-PH') };
console.log(copy.plate); // ENU-318-PH
console.log(typeof copy.describe); // undefined
The ... spread copies only the object's own keys. The data survives, but the methods are gone. A merge or deep-copy helper that checks isPlainObject before going inside a value avoids this.
The full solution
The panel has isPlainObject, a small isJsonObject extra that also checks the value can be turned into JSON, and four sample objects. Press Run to see each prototype and the checks.
const tag = (v) => Object.prototype.toString.call(v).slice(8, -1);
function isPlainObject(v) {
if (tag(v) !== 'Object') return false; // rules out arrays, dates, null, Map...
const proto = Object.getPrototypeOf(v);
// Either a normal {} literal, or a prototype-less bag from Object.create(null).
return proto === Object.prototype || proto === null;
}
// Everything JSON can produce is plain, so this is a good practical test.
const isJsonObject = (v) => isPlainObject(v) && (() => {
try { return JSON.stringify(v) !== undefined; } catch { return false; }
})();
class Bus {
constructor(plate) { this.plate = plate; }
}
const literal = { plate: 'LAG-441-XA' };
const bare = Object.create(null);
bare.plate = 'ABJ-772-KM';
const instance = new Bus('ENU-318-PH');
const parsed = JSON.parse('{"plate":"KAN-905-BD"}');
console.log('prototype of {} ===', Object.getPrototypeOf(literal) === Object.prototype);
console.log('prototype of Object.create(null) ===', Object.getPrototypeOf(bare));
console.log('prototype of new Bus() ===', Object.getPrototypeOf(instance) === Object.prototype, '<- Bus.prototype sits in between');
console.log('tag of a class instance :', tag(instance), '<- still "Object", so the tag alone is not enough');
console.log('--- and the bare object has no inherited methods at all ---');
console.log('literal.toString exists?', typeof literal.toString);
console.log('bare.toString exists? ', typeof bare.toString);
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an object literal is plain', isPlainObject(literal), true);
test('a JSON.parse result is plain', isPlainObject(parsed), true);
test('a prototype-less object is plain', isPlainObject(bare), true);
test('a class instance is NOT', isPlainObject(instance), false);
test('even though its tag says Object', tag(instance), 'Object');
test('an array is not plain', isPlainObject([]), false);
test('nor a date', isPlainObject(new Date()), false);
test('nor a Map', isPlainObject(new Map()), false);
test('nor null', isPlainObject(null), false);
test('nor a function', isPlainObject(() => {}), false);
test('a nested literal is still plain', isPlainObject({ a: { b: 1 } }), true);
test('a class instance has its own prototype in the chain', Object.getPrototypeOf(instance) === Bus.prototype, true);
test('a bare object inherits nothing, not even toString', typeof bare.toString, 'undefined');
test('while a literal does', typeof literal.toString, 'function');
test('the bare object still holds its data', bare.plate, 'ABJ-772-KM');
test('and the JSON check agrees with the plain check here', isJsonObject(literal), true);
The prototype is the only thing that separates { plate: 'X' } from new Bus('X') — both have tag 'Object' and both have a plate property. This matters when you are merging configuration or deep-cloning: recursing into a class instance as though it were a plain bag of data usually destroys it.
Object.create(null) is worth knowing separately. It inherits nothing, so it has no toString and no hasOwnProperty — the assertions above check that. It is the safe choice for a lookup table built from user-supplied keys, because a key called "toString" or "__proto__" cannot then collide with anything inherited.
Common mistakes
- Trusting the tag alone. A class instance has the tag
'Object'too. Check the prototype as well. - Forgetting
Object.create(null). Its prototype isnull, so a check forObject.prototypealone wrongly refuses it. - Calling
obj.hasOwnProperty(key)on a bare object. It has no such method. UseObject.hasOwn(obj, key).
Try it yourself
- Write
countPlain(values)that counts how many items in an array are plain objects. - Make a
Pointclass and check thatisPlainObjectrefuses an instance but accepts{ ...point }. - Write
lookup(words)that counts words in anObject.create(null)table, and try the word'toString'.