I often need to check if a value is a number in JavaScript. So instead of googling for it everytime, let's have a look at how two popular JavaScript frameworks implement that, jQuery and Underscore. Needless to say, that if you have any of these libraries included in your app, the best way to check for a number is to use their methods.
jQuery
The jQuery method uses substraction to force an infinity value to become a NaN
:
js
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return obj - parseFloat( obj ) >= 0;
}
Underscore.js
Underscore uses the toString
function of the object:
js
function isNumber(obj) {
return toString.call(obj) == '[object Number]';
}
Testing
Both methods pass all our tests. First, I place the two methods inside an object for easy looping
js
var isNumber = {
jq: function(obj) {
return obj - parseFloat( obj ) >= 0;
},
und: function(obj) {
return toString.call(obj) == '[object Number]';
}
};
Then I spec the tests for both methods in jasmine.
js
describe("isNumber", function() {
for (var fn in isNumber) {
// cache the function to be called
var func = isNumber[fn];
it("checks for a number", function() {
expect(func(1)).toBeTruthy();
});
it("checks for a 0", function() {
expect(func(0)).toBeTruthy();
});
it("checks for a negative number", function() {
expect(func(-816)).toBeTruthy();
});
it("checks for NaN", function() {
expect(func(NaN)).toBeTruthy();
});
it("checks for a number in a string", function() {
expect(func('1')).toBeFalsy();
});
it("checks for a hex number", function() {
expect(func(0xe100)).toBeTruthy();
});
}
});
Next time I need a number checker without an external library dipendency, I'll borrow one of these methods.