In Underscore.js library, there is a function named isFinite
returning 'true' if the value is a number. Considering that the built-in function isFinite
of Javascript is already returning 'true' if the value passed as argument is a number, why we also need to call !isNaN(parseFloat(obj))
?
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
This covers the case of
isFinite("")
,isFinite(null)
andisFinite(false)
all returningtrue
, becauseisFinite
blindly converts its argument to a number and treats any of these like0
.Starting with the numeric conversion...
...
isFinite
has some surprising results:Meanwhile,
_.isFinite
returns something more like you might expect, becauseparseFloat
returnsNaN
for all these valuesNote that you can get the same explicit checking with
Number.isFinite
, which doesn't attempt to convert its argument (but which is less well supported across browsers):