óCoffeeScript Cookbook

Check if type of value is an Array


You want to check if a value is an Array.

myArray = []
console.log typeof myArray // outputs 'object'

The typeof operator gives a faulty output for arrays.


Use the following code:

typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'

To use this, just call typeIsArray as such:

myArray = []
typeIsArray myArray // outputs true


The method above has been adopted from "the Miller Device". An alternative is to use Douglas Crockford's snippet:

typeIsArray = ( value ) ->
    value and
        typeof value is 'object' and
        value instanceof Array and
        typeof value.length is 'number' and
        typeof value.splice is 'function' and
        not ( value.propertyIsEnumerable 'length' )