Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save djD-REK/4b2072639d2920d6dd0b192256b1f271 to your computer and use it in GitHub Desktop.
Save djD-REK/4b2072639d2920d6dd0b192256b1f271 to your computer and use it in GitHub Desktop.
// Check for an integer by comparing the parsed version of itself with itself:
const isInteger = value => parseInt(value)==value
// Note the loose equality ==, which means values can be coerced before being
// compared. This implies strings that parse to integers will return true.
console.log(isInteger(37)) // true
console.log(isInteger(37.42)) // false
console.log(isInteger("37")) // true
console.log(isInteger(NaN)) // false
console.log(isInteger(Infinity)) // false
// To only select integer numbers, not strings that would parse into integers:
const isIntegerNumber = value => typeof value === 'number' && parseInt(value)==value
console.log(isIntegerNumber(37)) // true
console.log(isIntegerNumber("37")) // false
// Alternatively, use strict equality ===, which will also only return true for
// numbers, but not for strings that would parse into integers:
const isIntegerStrict = value => parseInt(value)===value
console.log(isIntegerStrict(37)) // true
console.log(isIntegerStrict("37")) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment