typeof for any non-trivial datatype returns
Check for Arrays Post ES5 (including Demandware)
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.
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.
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.