To check if a value is an object in JavaScript, you need to handle edge cases like null
(which is technically an “object” due to a historical quirk) and distinguish between plain objects (e.g., {}
, new Object()
) and other object-like types (e.g., arrays, dates, functions). Here’s a detailed guide:
1. Basic Check Using typeof
The typeof
operator returns "object"
for objects and null
, but not for primitives (e.g., strings, numbers).
function isObject(value) {
return typeof value === 'object' && value !== null;
}
// Examples:
console.log(isObject({})); // true (plain object)
console.log(isObject([])); // true (array is an object)
console.log(isObject(null)); // false (excluded via `value !== null`)
console.log(isObject(42)); // false (number is primitive)
console.log(isObject(new Date()));// true (Date object)
Limitation: This returns true
for arrays, dates, and other non-plain objects.
2. Check for Plain Objects Only
To check if a value is a plain object (e.g., {}
, new Object()
), use Object.prototype.toString
:
function isPlainObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
// Examples:
console.log(isPlainObject({})); // true
console.log(isPlainObject([])); // false (array → [object Array])
console.log(isPlainObject(null)); // false
console.log(isPlainObject(new Date())); // false (Date → [object Date])
How it works:Object.prototype.toString.call(value)
returns the internal [[Class]]
of the value (e.g., [object Object]
for plain objects).
3. Check for Any Object (Including Arrays, Dates, etc.)
If you want to include arrays, dates, and other non-plain objects:
function isAnyObject(value) {
return (typeof value === 'object' || typeof value === 'function') && value !== null;
}
// Examples:
console.log(isAnyObject({})); // true
console.log(isAnyObject([])); // true
console.log(isAnyObject(null)); // false
console.log(isAnyObject(() => {})); // true (functions are objects)
4. Using Lodash
The Lodash library provides a utility method for precise checks:
// Install Lodash: npm install lodash
const _ = require('lodash');
console.log(_.isObject({})); // true
console.log(_.isObject([])); // true
console.log(_.isObject(null)); // false
console.log(_.isObject(42)); // false
Key Scenarios
Value | typeof Check | isPlainObject | isAnyObject | Lodash _.isObject |
---|---|---|---|---|
{} | true | true | true | true |
[] | true | false | true | true |
null | false | false | false | false |
new Date() | true | false | true | true |
function () {} | false | false | true | true |
42 | false | false | false | false |
Summary
- For plain objects: Use
Object.prototype.toString.call(value) === '[object Object]'
. - For any object (including arrays, dates): Use
typeof value === 'object' && value !== null
. - For functions and objects: Extend the check to
typeof value === 'function'
.
Choose the method based on your specific use case!