How do you check if a value is an object in JavaScript?
Oh My God! I think this could be more shorter than ever, let see this:
function isObject(obj)
{
return obj != null && obj.constructor.name === "Object"
}
console.log(isObject({})) // returns true
console.log(isObject([])) // returns false
console.log(isObject(null)) // returns false
typeof JavaScript objects (including null) returns "object"
console.log(typeof null, typeof [], typeof {})
Checking on their constructor property returns function with their names.
console.log(({}).constructor) // returns a function with name "Object"
console.log(([]).constructor) // returns a function with name "Array"
console.log((null).constructor) //throws an error because null does not actually have a property
Function.name returns a readonly name of a function or "anonymous" for closures.
console.log(({}).constructor.name) // returns "Object"
console.log(([]).constructor.name) // returns "Array"
console.log((null).constructor.name) //throws an error because null does not actually have a property
Note: As of 2018, Function.name might not work in IE https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility