How to check if a value is object-like in JavaScript ?
In JavaScript, objects are a collection of related data. It is also a container for name-value pairs. In JavaScript, we can check the type of value in many ways. Basically, we check if a value is object-like using typeof, instanceof, constructor, and Object.prototype.toString.call(k). All of the operators are used in some specific conditions.
typeof operator: This is used to identify the type of variable. It returns a variable type. It is the easiest way to check the type of the variable. It works for some variables, but it did not identify the exact type of variable.
Conditions: It treated array, set, and null same as the object. typeof returns object for all of these. In the case of variable except three of this typeof is used.
- Syntax:
typeof VariableName;
- Example:
Javascript
<script> let k = {Name: 'gfg' ,Country: 'India' }; let k0 = new Set() let k1 = [1,2,3]; let k2 = "hello" ; let k3 = null ; let k4 = undefined; console.log( typeof k ) console.log( typeof k0 ) console.log( typeof k1 ) console.log( typeof k2 ) console.log( typeof k3 ) console.log( typeof k4 ) </script> |
Output:
object object object string object undefined
instanceof operator: This is used to check if any instance is made with a certain constructor or not. It returns true if it is made with constructor else returns false. It only works for those who are wrapped in regular object types.
Condition: It treats the array and sets the same as the object. So we can use instanceof operator for all values except these two.
- Syntax:
Variable instanceof object;
- Example:
Javascript
<script> let k = {Name: 'gfg' ,Country: 'India' }; let k0 = new Set() let k1 = [1,2,3]; let k2 = "hello" ; let k3 = null ; let k4 = undefined; console.log( k instanceof Object) console.log( k0 instanceof Object) console.log( k1 instanceof Object) console.log( k2 instanceof Object) console.log( k3 instanceof Object) console.log( k4 instanceof Object) </script> |
Output:
True True True false false false
constructor property: This is the property of the variable which points to the fundamental object constructor type of that object. We can check for those variables which have constructor property.
Condition: The constructor method throw an error for variables not having constructor property. null and undefined don’t have constructor property, so it throws an error.
- Syntax:
Variable.constructor === Object
- Example:
Javascript
<script> let k = {Name: 'gfg' ,Country: 'India' }; let k0 = new Set() let k1 = [1,2,3]; let k2 = "hello" ; console.log( k.constructor === Object) console.log( k0.constructor === Object) console.log( k1.constructor === Object) console.log( k2.constructor === Object) <script> |
Output:
True false false false
Please Login to comment...