Last active
December 5, 2019 16:11
-
-
Save djD-REK/4b2072639d2920d6dd0b192256b1f271 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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