Check if a value is an object in JavaScript
The simplest way to check if a value
is an object strictly (excluding null
, an array, or a function) involves a short combination of checks:
This neat little isPlainObject
function will only return true
if an object is genuinely created using {}
or new Object
.
Getting deeper in the rabbit hole
When handling JavaScript, things may not always be as they seem. Here's diving deeper into the object checking territory with more refined checks and explanations:
Ditching arrays and functions from the party
Despite functions and arrays secretly wish to be objects, we won't grant their wish:
Null, the imposter, and the wrapper objects
Null, disguised as an object, continues to fool us all, and the wrapper objects just add to the complexity:
Also, keep in mind about primitive wrapper objects. A deceptive new String('text')
will return an object, not a primitive string.
Accurate types with a bit of charm
The Object.prototype.toString
method can precisely nail down types. Use it to have distinct, reliable results:
The Underscore library offers an even robust function _.isObject
for this cumbersome task:
Be cautious with instanceof Object
, though. It's stingy and fails to recognize objects using Object.create(null)
.
Cracking the JavaScript code
Language quirks and misleading operators
More often than not, typeof
and instanceof
become tricksters, and null
keeps pretending to be an object. Outsmart them with a more cautious approach.
The ever-evolving JavaScript world
JavaScript engine bugs, especially V8, posed object check issues, but recent improvements helped get rid of them to a large extent.
Libraries to the rescue!
Libraries like Underscore and Lodash fight these oddities with their isObject
methods, providing a more consistent behavior across environments.
Was this article helpful?