Skip to main content

JavaScript - Is it an Array or an Object

Array vs Object type checking#

In pre-es6 days, there was no straight forward way of determining if a variable contains an array or an object.

Because typeof arr always gives you object even though arr contains an array.

So how did we check?

Well this is kind of a hack, but we need to use the combination of the Object's prototype method called toString and Function's prototype method called call.


As seen below, when you do on an array, it gives exactly this string: [object Array]. Whereas if you do it on an object, it gives this string: [object Object]. Always!

const arr = [1, 2, 3];
// Output: [object Array]
const obj = { a: 10, b: 20 };
// Output: [object Object]

ES6 way#

Luckily, the TC39 folks found this hack to be cumbersome and adopted a static method on Array called Array.isArray to find out a given value is indeed an array or not.

const arr = [1, 2, 3];
// Output: true
const obj = { a: 10, b: 20 };
// Output: false
Last updated on