How to check if a variable is an object in JavaScript?
typeof
function isObject(variable) {
return (
typeof variable === 'object' &&
variable !== null &&
!Array.isArray(variable)
);
}
Object()
function isObject(variable) {
return variable === Object(variable);
}
Object.prototype.toString()
function isObject(variable) {
return Object.prototype.toString.call(variable) === '[object Object]';
}
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call(null) // ️'[object Null]'
Object.prototype.toString.call('') // ️'[object String]'
Object.prototype.toString.call() // '[object Undefined]'