The best way to check if a variable is an object or not is to use the instanceof
operator.
The instanceof
operator expects two operands. So, on the left-hand side, specify the variable you want to check and on the right-hand side, mention Object
. If the variable is an object, then the instanceof
operator evaluates to true
otherwise false
.
variable instanceof Object
The following example shows how to check if a variable is an object or not:
let fullname = { firstName: "Khushboo", lastName: "Natani" }; let x = "JavaScript"; console.log(fullname instanceof Object); //true console.log(x instanceof Object); //false
It is recommended that you should not use the typeof
operator to check whether a variable is an object or not because the typeof
operator returns "object"
for all non-primitive values, and this will confuse you.
let fullname = { firstName: "Khushboo", lastName: "Natani" }; let x = [1, 2, 3, 4]; let y = null; console.log(typeof fullname); //"object" console.log(typeof x); //"object" console.log(typeof y); //"object"
In this example, you can see that the typeof operator returns "object"
for an array x
.