To check if a variable is an object, you can use the typeof operator followed by the variable and we also need to check if the variable is not null value because null is of type object in JavaScript.
// Check if variable is an object
const variable = {
name: "John Doe",
age: 23,
};
typeof variable === "object" && variable !== null; // true
/*
Boolean true means the variable is of object type
*/
- If the above condition returns
true, then thevariableis of typeobject. - This is a better way to check if a variable is of type
object.
See the above code live in JSBin.