Typeof Wrapper
06/20/2014, Fri
Categories:
#JavaScript
Robust Typeof
Using typeof in JavaScript does not produce the results that one would expect as explain by many articles found on the internet.
This snippet adapts underscore's checking of types in a condense function to provide a more compact and predictable means of checking types in JavaScript.
// Robust Typeof Wrapper Function
var type = (function () {
// Alias the object's prototype
var objProto = Object.prototype.toString;
// Mapping object for type checking
var typeObj = {
array: function (obj) {
return Array.isArray(obj) || objProto.call(obj) == "[object Array]";
},
object: function (obj) {
return obj === Object(obj);
},
boolean: function (obj) {
return (
obj === true ||
obj === false ||
objProto.call(obj) == "[object Boolean]"
);
},
null: function (obj) {
return obj === null;
},
undefined: function (obj) {
return obj === void 0;
},
nan: function (obj) {
return this.number(obj) && obj != +obj;
},
};
var commonCompareTypes = ["function", "string", "number", "date", "regexp"];
for (var i = 0; i < commonCompareTypes.length; i++) {
(function () {
var currentType = commonCompareTypes[i];
var fn = function (obj) {
return objProto.call(obj).slice(8, -1).toLowerCase() === fn.type;
};
fn.type = currentType;
typeObj[currentType] = fn;
})();
}
return function (value, type) {
return typeObj[type](value);
};
})();
// Examples
// Second parameter needs to be in lowercase for function to work
type("stuff", "date"); //false
type({}, "array"); //false
type({}, "object"); //true
type([], "object"); //true
type(null, "null"); //true
type(NaN, "nan"); //true
type(123, "nan"); //false
Do note the behaviors of the 'object' and 'nan' check, as this follows underscore's checking implementation. Objects and arrays are considered objects. The 'nan' check is looking for the 'NaN' value, and when this condition is not satisfied, false will be returned.