Yes, there is. Since this is an index value, presumably you would like to accept any number. This could suggest that typeof indexValue === "number"
is the right approach, since this will reject both null
and undefined
, but will accept 0
. However, this condition will also accept other undesirable values, such as NaN
, Infinity
, and -Infinity
, which are all numbers as well.
Thankfully, the language provides us with a bulit-in function that can test all of these at once: isFinite()
. So your condition becomes:
if (isFinite(indexValue)) {
// ...
}
Note that this function will accept strings that convert to finite numbers. There is also Number.isFinite()
, which accepts only numbers, but is not supported in IE. If you want to reject all strings, then combine the isFinite()
check with the typeof
check:
if (typeof indexValue === "number" && isFinite(indexValue)) {
// ...
}