This article shows how you can check if a Javascript variable is of an Object type.
There are different ways to check if a variable is an Object in Javascript.
1) First way
// define an object
var myObject = {id: 11, name: John}
console.log(Object.prototype.toString.call(myObject)); // [object Object]
// check if the variable is an object
if (Object.prototype.toString.call(myObject) === '[object Object]') {
console.log('The variable is an object.');
} else {
console.log('The variable is NOT an object.');
}
// for array, you will get [object Array]
var myArray = [1, 2, 3];
console.log(Object.prototype.toString.call(myArray)); // [object Array]
2) Second way
We use typeof
to check the type of the variable.
We also check for Array using isArray()
function because both Array and Object has typeof = object
.
Array.isArray()
method was introduced in ECMAscript 5 (ES5).
function isObject(obj) {
return obj !== null && typeof obj === 'object' && Array.isArray(obj) === false;
}
console.log(isObject(myObject)); // true
var myArray = [1, 2, 3];
console.log(isObject(myArray)); // false
3) Third way
Using instanceof
operator
// using object instanceof and constructor operator
function isObject(obj) {
return obj instanceof Object && obj.constructor === Object;
}
console.log(isObject(myObject)); // true
console.log(isObject(myArray)); // false
Using typeof
operator
// using object typeof and constructor operator
function isObject(obj) {
return typeof obj === 'object' && obj.constructor === Object;
}
console.log(isObject(myObject)); // true
console.log(isObject(myArray)); // false
Here’s the difference between typeof
and instanceof
:
instanceof
operator tests the presence of constructor.prototype in object’s prototype chain.
typeof
operator returns a string indicating the type of the operand. The operand can be an object or primitive value like string, number, null, undefined, etc.
const a = "Primitive String";
const b = new String("String Object");
console.log(typeof a); // output: string
console.log(typeof b); // output: object
console.log(a instanceof String); // output: false
console.log(b instanceof String); // output: true
Hope this helps. Thanks.