Last Updated: February 25, 2016
·
635
· copenhas

JavaScript Type checking

I know, I know. You should be doing duck typing and letting things blowup. Or only checking for the specific things you want. And yet I tend to find myself doing a bit of type checking around argument parsing.

Anyway I've had some success with type checking using the parent Object.prototype.toString with a few special cases. Here's the code I ended up using in my argument parsing library "funs":

function getType(o) {
    var rawTypeString = 
        Object.prototype.toString.call(o);

    var typeString = 
        rawTypeString.replace('[object ', '')
                     .replace(']', '')
                     .toLowerCase();

    if (typeString === 'number' && Number.isNaN(o)) {
        return 'nan';
    }

    if (o instanceof Error) {
        return 'error';
    }

    if (typeString.indexOf('html') === 0) {
        return 'dom';
    }

    return typeString;
}

Full code in use at: https://github.com/copenhas/funs

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside