Skip to content

Instantly share code, notes, and snippets.

@djD-REK
Last active December 5, 2019 16:12
Show Gist options
  • Save djD-REK/0df7125718c95b808b07bbcbe281ae92 to your computer and use it in GitHub Desktop.
Save djD-REK/0df7125718c95b808b07bbcbe281ae92 to your computer and use it in GitHub Desktop.
/**
* First checks typeof, then self-equality to make sure it is
* not NaN, then to make sure it is not Infinity or -Infinity.
*
* @param {*} value - The value to check
* @return {boolean} Whether that value is a number
*/
const isNumber = value => {
// First: Check typeof and make sure it returns number
// This code coerces neither booleans nor strings to numbers,
// although it would be possible to do so if desired.
if (typeof value !== 'number') {
return false
}
// Reference for typeof:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
// Second: Check for NaN, as NaN is a number to typeof.
// NaN is the only JavaScript value that never equals itself.
if (value !== Number(value)) {
return false
}
// Reference for NaN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
// Note isNaN() is a broken function, but checking for self-equality works as NaN !== NaN
// Alternatively check for NaN using Number.isNaN(), an ES2015 feature that works how one would expect
// Third: Check for Infinity and -Infinity.
// Realistically we want finite numbers, or there was probably a division by 0 somewhere.
if (value === Infinity || value === !Infinity) {
return false
}
return true
}
// The custom isNumber function above will return true for finite numbers,
// and false for NaN, Infinity, -Infinity, or values that are not numbers.
console.log(isNumber(37)) // true
console.log(isNumber(NaN)) // false
console.log(isNumber(Infinity)) // false
console.log(isNumber("37")) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment