javascript check if object

Javascript Check If Object

As a web developer, I have come across a situation where I needed to check if a variable is an object or not in Javascript. There are many ways to do this, and I will explain some of them below.

Using typeof Operator

The typeof operator returns a string indicating the type of the operand. We can use this operator to check if a variable is an object or not.


let obj = {name: "Raju", age: 25};
if(typeof obj === "object") {
    console.log("obj is an object");
}

In the above code, we are checking if the obj variable is of type object using the typeof operator. If it is an object, we are logging a message to the console.

Using instanceof Operator

The instanceof operator checks if an object is an instance of a specified object type. We can use this operator to check if a variable is an object or not.


let obj = {name: "Raju", age: 25};
if(obj instanceof Object) {
    console.log("obj is an object");
}

In the above code, we are checking if the obj variable is an instance of the Object type using the instanceof operator. If it is an object, we are logging a message to the console.

Using toString() Method

The toString() method returns a string representing the object. We can use this method to check if a variable is an object or not.


let obj = {name: "Raju", age: 25};
if(Object.prototype.toString.call(obj) === "[object Object]") {
    console.log("obj is an object");
}

In the above code, we are calling the Object.prototype.toString() method on the obj variable to get its string representation. We are then checking if the string representation is equal to [object Object], which indicates that the variable is an object.

Conclusion

These are some of the ways to check if a variable is an object or not in Javascript. It is important to use the correct method based on your use case and requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe