This tutorial will demonstrate the methods for getting the name of the object’s type in JavaScript.
How to Get/Retrieve the Name of an Object’s Type in JavaScript?
To get the name of the object type, use the following mentioned approaches:
Method 1: Get the Name of an Object’s Type Using “typeof” Operator
Use the “typeof” operator, to retrieve the name of an object’s type. It gives a string that indicates the type of the operand or variable.
Syntax
Utilize the following syntax for getting the name of an Object’s type using the “typeof” operator:
Example
Here, in the given example, we will first create a variable “a” and assign it a number “15”:
Then, check the type of the variable utilizing the “typeof” operator:
It can be shown that the output displays “number” that indicates the data type of the variable “a”:
Now, we will store a string in variable “a” and check the type:
console.log(typeof a);
The specified operator returns the type of “a” as “string”:
It should be noted that the “typeof” operator may not always return the exact name of the object’s type. For instance, it will output “object” for arrays.
Let’s see an example to see this concept.
Create an array and store it in a variable “a”:
Check the type of variable “a” using the “typeof” operator:
As you can see that the output displays “object” not specify its type:
So, in that case, use the “constructor ” property for retrieving the type of an object.
Method 2: Get the Name of an Object’s Type Using “constructor ” Property
Utilize the “constructor” property with the “name” attribute to get the name of the object’s type. It gives the name of the constructor function that created the object.
Syntax
The given syntax is utilized for using the “constructor” property to get the name of the object type:
Example
Use the “constructor” property to get the name of the object type:
As you can see, the specified property outputs “Array”, which is the actual type of the object “a”:
Method 3: Get the Name of an Object’s Type Using “Object.prototype.toString.call()” Method
You can also use the “Object.prototype.toString.call()” method for determining the data type of a given variable or operand. The “Object.prototype.toString.call()” method is more efficient than the typeof operator.
Syntax
Follow the given syntax for getting the name of an object type:
Example
Assign a string to the variable “a” and check the type of the object:
Object.prototype.toString.call(a);
Output
Here, we will check the type of “a” that stores an array:
Object.prototype.toString.call(a);
It gives the accurate result of the name of the object type:
That was all about getting the name of the object type in JavaScript.
Conclusion
For getting or retrieving the name of the object type, use the “typeof” operator, “constructor” property with the “name” attribute, or the “Object.prototype.toString.call()” method. This tutorial demonstrated the methods for getting the name of the object’s type in JavaScript.