I’m working with an output that could be null, 0, or a JSON object, and I need to determine if it is indeed a valid object. Is there an isObject
function like isArray
in JavaScript, or is there another method to check if it’s an object?
I’ve hit this scenario many times while doing data validation in JS-heavy apps—here’s a quick manual check I’ve relied on:
function isObject(val) {
return val !== null && typeof val === 'object' && !Array.isArray(val);
}
Why it works well:
- Filters out
null
(sincetypeof null
is'object'
) - Excludes arrays
- Focuses on plain objects only
If you’re just starting with javascript isobject
checks, this approach is reliable and minimal.
Nice one, Priyanka. I’ve used a slightly stricter version when I needed bulletproof type checks across complex data inputs, especially when libraries or polyfills might override native behavior.
function isObject(val) {
return Object.prototype.toString.call(val) === '[object Object]';
}
Why level it up?
- Safer in edge cases where
typeof
might be overridden - Still avoids arrays and functions
- Especially handy when dealing with sandboxed frames or unusual environments
If you’re deep-diving into javascript isobject
logic and need something stricter for validation pipelines, this works great.
Totally agree with both of you! When working in larger codebases (or with data crossing between windows/iframes), I usually bring in Lodash-it’s just easier and saves time handling quirks.
_.isPlainObject(val);
Why use Lodash’s
isPlainObject
?
- Handles cross-realm objects (like from iframes)
- Ignores arrays, functions, class instances, etc.
- Clean and production-safe
Yes, it does mean adding Lodash (npm install lodash
), but if you’re already using it, this is probably the most robust way to handle javascript isobject
checks without reinventing the wheel.