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)
and isFinite(false)
all returning true
, because isFinite
blindly converts its argument to a number and treats any of these like 0
.
Starting with the numeric conversion...
Number("") // 0
Number(false) // 0
Number(null) // 0
Number(undefined) // NaN
... isFinite
has some surprising results:
isFinite("") // true
isFinite(false) // true
isFinite(null) // true
isFinite(undefined) // false
Meanwhile, _.isFinite
returns something more like you might expect, because parseFloat
returns NaN
for all these values
_.isFinite("") // false
_.isFinite(false) // false
_.isFinite(null) // false
_.isFinite(undefined) // false
Note 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):
Number.isFinite("") // false
Number.isFinite(false) // false
Number.isFinite(null) // false
Number.isFinite(undefined) // false