DEV Community

Cover image for Get exactly object typeof in JavaScript/JS
RASEL MAHMUD
RASEL MAHMUD

Posted on

Get exactly object typeof in JavaScript/JS

In these tips, I will share a built-in method in JavaScript that will help you get exact object data type extract for validation or type checking.

So, let's start as you can see below picture where I use type for data type checking but when we want to check between the Array and Object it will show the same output object data type because JavaScript is treated as the object but as a human we see different data type.

using typeof for object data type checking

Now we can handle this data type checking using the getPrototypeOf method and its constructor property. Below the picture, you can see the different types of data shown in the output Object is return true and Array is return false. Keep in mind it is very useful when you need exactly object and array type checking.

using constructor method for object data type checking

Are you thinking of real life use case?

Well, let's see the use case suppose you have an API endpoint you don't know after fetching the data will show in an array or object. Or you have an endpoint but the endpoint randomly gives data using sometimes object and sometimes array, now you need to ensure which type of data comes each time.

Below the image, I demonstrate using a fake API that gives random output in array and object. I check if the data type array just simply passes it to another function for the next task. Else if the condition checks the exact object data type and spread that object then wraps it in the array.

exactly object data type checking real life example

Top comments (0)