Check if something is an Array, Object, or Function in JavaScript

There are a few techniques for this, but here's what I always fall back. Writing this down for posterity.

function isArray(sut) {  
    return Object.prototype.toString.call(sut) === '[object Array]';
}

function isObject(sut) {  
    return Object.prototype.toString.call(sut) === '[object Object]';
}

function isFunction(sut) {  
    return Object.prototype.toString.call(sut) === '[object Function]';
}

function isDate(sut) {  
    return Object.prototype.toString.call(sut) === '[object Date]';
}

function isBoolean(sut) {  
    return Object.prototype.toString.call(sut) === '[object Boolean]';
}

function isNumber(sut) {  
    return Object.prototype.toString.call(sut) === '[object Number]';
}

function isString(sut) {  
    return Object.prototype.toString.call(sut) === '[object String]';
}

function isRegex(sut) {  
    return Object.prototype.toString.call(sut) === '[object Regex]';
}

function isNull(sut) {  
    return Object.prototype.toString.call(sut) === '[object Null]';
}

function isUndefined(sut) {  
    return Object.prototype.toString.call(sut) === '[object Undefined]';
}

These functions use object's version of toString.

comments powered by Disqus