[JavaScript] Check if a variable is a type of an Object or Array?

In this Story, lets talk about how we can find out if a variable holds array or object values? Lets declare two separate variables named array and obj.

const array = [1,2,3,4,5];
const obj = {id: 1, name: “Josh”};

Now, you might be thinking that we can use typeof operator to find out whether its an array or object, Right? Lets see

console.log(typeof array);
console.log(typeof obj);

Using jsbin we can test our javascript code very easily

What???? Is typeof operator is mad? How it cannot differentiate between an object and an array? I am sure this question must be hitting your mind if you have just started exploring JavaScript world.

Let me solve this puzzle for you, Always remember, When we talk about “Derived data types (Objects, Array, Functions etc), They are always of type object”.

So how can we check if a variable is of type array or object, Well that’s the question we are here to Solve.

I will show you not one but three different ways using which you can find out the type. Lets consider we have this data variable that contains array and object.

  1. Using instanceof Operator:
const data = [1,2,3,4,5];
const isArray = data instanceof Array;
console.log(isArray); // true
const data = {id: 1, name: “Josh”};
const isArray = data instanceof Array;
console.log(isArray); // false

2. Using isArray method of Array

const data = [1,2,3,4,5];
const isArray = Array.isArray(data);
console.log(isArray); // true
const data = {id: 1, name: “Josh”};
const isArray = Array.isArray(data);
console.log(isArray); // false

3. Using Object.prototype.call method

const data = [1,2,3,4,5];
const isArray = Object.prototype.toString.call(data) === '[object Array]';
console.log(isArray); // true
const data = {id: 1, name: “Josh”};
const isArray = Object.prototype.toString.call(data) === '[object Array]';
console.log(isArray); // false

In all above examples, isArray will be set to true if the data variable has assigned Array of values, otherwise it will be false (in case of object).

I hope that after reading this story, you are very cleared about how we can conditionally check if a variable is of array or object type. Leave some claps if you find it useful, I will continue to post some amazing logical things during my journey to “Full Stack Developer”.

Developer? Trying to be One! Work: https://play.google.com/store/apps/developer?id=Amandeep+Kochhar