Skip to content

Instantly share code, notes, and snippets.

@jackfranklin
Created December 3, 2012 12:18
Show Gist options
  • Save jackfranklin/4194664 to your computer and use it in GitHub Desktop.
Save jackfranklin/4194664 to your computer and use it in GitHub Desktop.
Checking for NaN in JS
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