More Accurate Type Checking Than the typeof Operator
# More Accurate Type Checking Than the typeof Operator
The return values of Object.prototype.toString for different data types are as follows:
- Number: returns
[object Number]. - String: returns
[object String]. - Boolean: returns
[object Boolean]. - undefined: returns
[object Undefined]. - null: returns
[object Null]. - Array: returns
[object Array]. - arguments object: returns
[object Arguments]. - Function: returns
[object Function]. - Error object: returns
[object Error]. - Date object: returns
[object Date]. - RegExp object: returns
[object RegExp]. - Other objects: returns
[object Object].
This means that Object.prototype.toString can reveal the actual type of a value.
Object.prototype.toString.call(2) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Using this characteristic, you can write a type-checking function that is more accurate than the typeof operator.
var type = function (o){
var s = Object.prototype.toString.call(o)
return s.match(/\[object (.*?)\]/)[1].toLowerCase()
}
type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date"
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Building on this type function, you can also add methods that check for specific data types.
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
['Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp'
].forEach(function (t) {
type['is' + t] = function (o) {
return type(o) === t.toLowerCase();
};
});
type.isObject({}) // true
type.isNumber(NaN) // true
type.isRegExp(/abc/) // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36