How to get exact Object typeof in JavaScript/JS

How to get exact Object typeof in JavaScript/JS

You will get an idea also JavaScript advance usecase in this Article

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.

Problem Raised:

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

Solution

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 a 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 an 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 spreads that object then wraps it in the array.

const getProducts =()=>{
//hit the apt endpotnt using queryfetch(
fetch(`https://api.ecommerce.com/random-products`)
.then((res)=> res.json( ))
.then((data)=> {if(data instanceof Array)
{//checking the response if data is array
console.log(data);
}
else if(0bject.getPrototype0f(data).constructor === 0bject){
//checking strictly get object data type
const createArray =[{...data }];//spread the objects value and key
console.log(createArray);
};
getProducts();//invoking the function