Just surprised how many upvotes for wrong answers 😮
<br> Only [1 answer](https://stackoverflow.com/a/16608074/3612353) passed my tests!!! Here I've created my simplified version:
function isObject(o) {
return o instanceof Object && o.constructor === Object;
}
As for me, it's clear and simple, and just works! Here my tests:
console.log(isObject({})); // Will return: true
console.log(isObject([])); // Will return: false
console.log(isObject(null)); // Will return: false
console.log(isObject(/.*/)); // Will return: false
console.log(isObject(function () {})); // Will return: false
ONE MORE TIME: not all answers pass this tests !!! 🙈
<hr>
In case you need to verify that object is **instance of particular class** you have to check constructor with your particular class, like:
function isDate(o) {
return o instanceof Object && o.constructor === Date;
}
simple test:
var d = new Date();
console.log(isObject(d)); // Will return: false
console.log(isDate(d)); // Will return: true
As result, you will have strict and robust code!
<hr>
In case you won't create functions like `isDate`, `isError`, `isRegExp`, etc you may consider option to use this generalized functions:
function isObject(o) {
return o instanceof Object && typeof o.constructor === 'function';
}
it won't work correctly for all test cases mentioned earlier, but it's good enough for all objects (plain or constructed).
<hr>
`isObject` won't work in case of `Object.create(null)` because of internal implementation of `Object.create` which is explained [here](https://stackoverflow.com/questions/2709612/using-object-create-instead-of-new/45359635#45359635) but you can use `isObject` in more sophisticated implementation:
function isObject(o, strict = true) {
if (o === null || o === undefined) {
return false;
}
const instanceOfObject = o instanceof Object;
const typeOfObject = typeof o === 'object';
const constructorUndefined = o.constructor === undefined;
const constructorObject = o.constructor === Object;
const typeOfConstructorObject = typeof o.constructor === 'function';
let r;
if (strict === true) {
r = (instanceOfObject || typeOfObject) && (constructorUndefined || constructorObject);
} else {
r = (constructorUndefined || typeOfConstructorObject);
}
return r;
};
There is already created [package on npm](https://www.npmjs.com/package/is-it-object) based on this implementation! And it works for all earlier described test cases! 🙂