in Coding, Software

Check for Arrays in JavaScript

JavaScript is a great language, but it’s far from perfect. One among many other drawbacks is JavaScript’s nature of assigning and handling datatypes. typeof for any non-trivial datatype returns object which makes it a bit unintuitive to detect whether or not a given variable contains an array. Here is how to check for Arrays in JavaScript…

Check for Arrays Post ES5 (including Demandware)

Luckily, since ES5 JavaScript provides the static method Array.isArray() to overcome this lack.

I’m currently working for a company implementing Demandware (Salesforce Commerce Cloud) Applications. The backend scripting language we use is referred to as Demandware Script. Officially, the Documentation doesn’t list the isArray() method being part of the class Array, so I was confused for a very long time whether or not this were supported.

A bit of a research in the closed Developer Wiki revealed that the Demandware Java Core is basically wrapped by Rhino Javascript (currently Rhino release 1.7R5). Therefore, their technology stack includes ECMAScript 5, Mozilla extensions (up to Javascript 1.8) and E4X. Accordingly, the Array.isArray() method must be included, and indeed: Even though not documented, I tried and it works. :)

Check for Arrays Pre ES5

So for modern JS and Demandware, problem solved. But what about older projects dealing with < ES5? Well, there is a bit of a discussion, but basically three answers:

(1) If you are dealing with client-side JS and using jQuery, $.isArray() is your friend.

(2) You often read the advice checking myArray.constructor === Array which works for the most part, but it fails to identify arrays that were constructed in a different window or frame.

(3) Otherwise, You might consider writing a couple of lines for this by your own. Douglas Crockford comes up with a great and simple approach in his book „JavaScript the Good Parts“:

The basic idea is checking every relevant part of an array to be sure the check is unique. The first check makes sure the parameter isn’t empty. The others cover the existence of the length-property, as well as the splice-method. Finally, we make sure that the length-property is not enumerable, i.e. it will not be produced by a for in loop. Done.

For more background information and other approaches, it’s worth checking out the associated StackOverflow discussion.

Write a Comment