Skip to content

How to check if variable is an Array in JavaScript

So you want to check whether a variable is an Array or not. Here ECMAScript 5 gives you a hand 👏. Using Array.isArray() method we can achieve this.

Below is a code snippet to know if a variable is an array or not. For older browser, you can use the MDN polyfill.

let list1 = ['a','b','c'];
Array.isArray(list1);  //true
//polyfill === '[object Array]'; //true

Best👌way to check Array

Array.isArray([]); // true
Array.isArray(['a']); // true
Array.isArray(new Array('a')); // true

Browser Support

Internet Explorer 9✔️

Other Ways using Lodash or Underscore

If you’re using an external library, they also have some built-in methods too. Same syntax for both Lodash and Underscore

const array = ['a', 'b', 'c'];
const notArray = 'not array';

_.isArray(array); // true
_.isArray(notArray); // false

Why can’t we use typeof?

Array is actually come under the data type of Object. So typeof is indeed returning truthfully.

Problem with instanceof

When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes.

var iframe = document.createElement('iframe');
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true ✅
// Considered harmful, because doesn't work through iframes
arr instanceof Array; // false ❌

Problem with Array.length

So if an array has a length, we can assume that it’s an array?

😷Unfortunately, the problem with this solution is that there are other data types that have lengths ie. strings. So this can lead to false positive. Even an object can have length property😱

const string = 'Character';
string.length; // 9

Using Array.isArray() 👍 highly recommended.

Hope this article is useful to you✌️. Happy Coding 😄

See also  How to convert JavaScript Array to comma separated string?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.