Typeof Wrapper

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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.