Created
December 3, 2012 12:18
-
-
Save jackfranklin/4194664 to your computer and use it in GitHub Desktop.
Checking for NaN in JS
This file contains 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
var x = parseFloat("notanumber"); | |
x // NaN | |
x === NaN // false | |
isNaN(x) // true | |
// isNaN seems like it works, but doesn't actually because of type coercion: | |
isNaN("foo") // true | |
isNaN(undefined) // true | |
// so isNaN works fine for values you know to be a number, else it sucks. | |
// the most reliable way to check if any variable is NaN, is to check it is not equal to itself | |
var x = NaN | |
x !== x // true | |
var y = "foo" | |
y !== y // false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment