Press "Enter" to skip to content

JavaScript: check if variable is object or array

🠗 Skip reading – scroll down to solution 🠗

Why it is so important to verify if variable is an object or array?

In JavaScript it is easy to be flooded. The same is with objects and arrays. Many times we must check if some variable is an object or array. Short example – we receive some data from REST API via AJAX call, and we suppose this is an object, we can use its properties like:

response.data

but response object can be not an object but e.g. string “nothing found”. And the result will be “undefined” as string does not contain “data” property. Worse case would be if we want to dig deeper in that variable (which is supposed to be an object), e.g.:

response.data.employees

With that we will get Type Error:

Uncaught TypeError: Cannot read property 'employees' of undefined

Even worse it is with arrays – we can try to run Array methods like “map” on variable received from AJAX request, like on code below:

const employees = response.data.map((item, i) => {
    return `Employee number: ${i} - ${item}`
});

But… “response.data” from AJAX call is in reality not a ARRAY, but… STRING! And you will get next Type Error:

Uncaught TypeError: x.map is not a function

How to be sure that variable is object or array?

You can think now:

WTF? Just use operator “typeof”!

Yes… but it is not so easy and not so clear with JavaScript. Of course, you can check type of variable which is supposed to be an object, but this is a little tricky thing in JavaScript, because, in general, JavaScript… everything is “object”. And type “object” is not reserved for this what we, developers, treat as object like “{…}”.

Wanna example? Press F12 here, open the developers tools and open console window and put there code below:

console.log(typeof null); // object
console.log(typeof []); // object
console.log(typeof {}); // object

Interesting? So in our example with REST API ajax request, when it would return “null” or “array” but we expect object, then writing only, e.g.: if(typeof response.data) would be far to less.

JavaScript solution: check if variable is object or array

We need to do a few steps:

  1. Check if variable is null.
  2. For identifying objects: check if variable is not an array.
  3. For identifying arrays: check if variable is an array.
  4. Check if variable type is “object”.

Solution code below, you can just copy-paste and reuse that in your project:

const isNull = (val) => (!val && typeof val === "object");

const isObject = (data) => !Array.isArray(data) && ( typeof data === "object") && !isNull(data);

const isArray = (data) => Array.isArray(data) && ( typeof data === "object") && !isNull(data);