Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript checks whether the type of variable is an array


May 09, 2021 CoffeeScript


Table of contents


Check if the type of variable is an array

Problem

You want to check if a variable is an array.

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

The "typeof" operator outputs an incorrect result for the array.

Solution

Use the following code:

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

To use this, call type IsArray like this.

myArray = []
typeIsArray myArray // outputs true

Discuss

The above method is taken from "The Miller Device". Another way is to use Dougglas Crockford's fragments.

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' )