Array.isArray

JavaScript polyfill, by , Sunday, March 23rd, 2014

If you are using the neat build in method to determine if an object is an array or not, but you also know, that an important part of your user base uses older versions of IE, then you might want to play it save and use a polyfill for the method. Luckily writing a polyfill for this particular method is really simple if you know which pitfalls to avaoid. As you properly know the build in typeof operator returns Object on arrays, so that is not an option. Also if it was, this functionality would not be necessary anyway.

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

This piece of code requires a short explanation. What is done here is, that we are using the Object object's toString method to turn the passed argument into a string. If you have an Object object, it would return "[object Object]", but when it is an array it returns "[object Array]". It does this, because an array is an object in JavaScript, which the first parameter in the string indicates. The second parameter on the other hand, indicates which class of Object the passed object is, and in the case of an array it is of course of class Array. (you can read more about object classes in my article How to get the class of an object value)If you read the actual documentation for how the Array.isArray method is implemented, you will find this; (this is an outtake from the ECMAScript 5.1 specification section 15.4.3.2)

  1. If Type(arg) is not Object, return false.
  2. If the value of the [[Class]] internal property of arg is "Array", then return true.
  3. Return false.

As you can see, this is almost exactly how the polyfill works, except we do not have direct access to the [[Class]] property of the argument object, so we need to turn it into a string that reveals its class. We can be sure that this is exactly what happens by looking at how the Object.prototype.toSting method works; (this is an outtake from the ECMAScript 5.1 specification section 15.2.4.2)

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. Let O be the result of calling ToObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

If we pay special attention to line 5, we see that indeed the string returned is "[object " plus the class of the argument. With this understanding it is quite obvious why and how the above polyfill works.