typeof function fix / alternative

javascript

Solution

See Fixing the JavaScript typeof Operator.

In a nutshell, you can use this function:

var toType = function (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

toType(null);   // -> "null"
toType({});     // -> "object"
toType([]);     // -> "array"
toType("asdf"); // -> "string"
toType(/asdf/); // -> "regexp"
// etc.

You should see the article for the specifics on why it works the way it does and exactly what you can expect from it. It will always return a string, just like `typeof`.

Problem

The `typeof` doesn't work perfectly well, `typeof null` returns on `object` for example. Is there any better alternative to this kind of improved alternative built-in or custom made ?

Original source