How to check if an object is an array in JavaScript

published: 04 Oct 2022

2 min read

How to check if an object is an array in JavaScript

You may have used the typeof operator in JavaScript to check the type of an object. But, unfortunately, it doesn't work for arrays. The real issue is the way arrays are handled in JavaScript.

A JavaScript array is internally treated as a special kind of object. The square brackets syntax used for accessing an array element array[index] closely resembles what we use for an object object[key]. The only tangible difference is that index numbers are used as keys.

The simplest way to check if a variable is an array in JavaScript is by using the Array.isArray() method:

Array.isArray(['🍵', '🍔', '🍕']); // true
Array.isArray([]); // true
Array.isArray({ name: 'John Deo', age: 21 }); // false

The Array.isArary() method works in all modern browsers, and IE9 and up. For older browsers support, just use the following polyfill:

if (!Array.isArray) {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    };
}

Take a look at this article to learn more about JavaScript arrays and how to use them to store multiple values in a single variable.

How to check if an object is an array in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array