How do I check if a variable is an object in JavaScript?
Davide S
davide s profile pic

In JavaScript, you can check if a variable is an object using various methods. Here are a few common approaches: 1. Using thetypeof operator: - Thetypeof operator returns a string indicating the type of a variable. - You can use it to check if a variable's type is"object".

1
2
3
4
5
6

   const variable = {}; // Object
   if (typeof variable === "object" && variable !== null) {
     // Variable is an object
   }
   

In this example,typeof variable === "object" checks if the variable's type is"object", andvariable !== null ensures that it is notnull. Note: Thetypeof operator returns"object" for arrays, null, and objects. To specifically check for a plain object, you need to exclude null and arrays. 2. Using theObject.prototype.toString() method: - TheObject.prototype.toString() method returns a string representation of the object's type. - By calling it on the variable and comparing the result to"[object Object]", you can determine if the variable is an object.

1
2
3
4
5
6

   const variable = {}; // Object
   if (Object.prototype.toString.call(variable) === "[object Object]") {
     // Variable is an object
   }
   

Here,Object.prototype.toString.call(variable) returns the string representation of the variable's type. Comparing it to"[object Object]" ensures that the variable is an object. 3. Using theinstanceof operator: - Theinstanceof operator tests whether an object is an instance of a particular constructor. - You can use it to check if the variable is an instance of theObject constructor.

1
2
3
4
5
6

   const variable = {}; // Object
   if (variable instanceof Object) {
     // Variable is an object
   }
   

In this example,variable instanceof Object checks if the variable is an instance of theObject constructor. Choose the method that best suits your requirements. Thetypeof operator andObject.prototype.toString() method are widely used for checking object types. Theinstanceof operator can also be useful in specific cases when you want to ensure that the variable is an instance of a particular constructor.