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.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.