13

How can I check if a value is NaN? I'd prefer a solution that can be used in Clojure too without much extra stuff (so I don't want to use an external library, such as underscore). Here is what I tried

(number? js/NaN) ;=> true, well I'd expect false
(= js/NaN (js/parseInt "xx")) ;=> false
(= js/NaN js/NaN) ;=> false, even worse

; This is the best I could come up with
(defn actual-number? 
  [n] 
  (or (> 0 n) (<= 0 n)))
Adam Schmideg
  • 10,590
  • 10
  • 53
  • 83

3 Answers3

23

You shouldn't compare NaN's - they're always unequal. You should be able to use javascript's built-in isNaN function like

(js/isNaN x)
Joost Diepenmaat
  • 17,633
  • 3
  • 44
  • 53
3

You can use isNaN js function:

(js/isNaN ..)

Ankur
  • 33,367
  • 2
  • 46
  • 72
2

Be aware that

(js/isNaN [1,2])

returns true. There are other many cases where js/isNaN does not correspond to what one expects.

If you're using underscore.js in the browser, you can delegate to (.isNaN js/_ ..) instead.

Otherwise, the following function should to the trick:

(defn isNaN [node]
  (and (= (.call js/toString node) (str "[object Number]"))
       (js/eval (str node " != +" node ))))
pedroteixeira
  • 806
  • 7
  • 7