Mark a number invalid (besides -1): Infinity or NaN?

Viewed 75

I need to mark a number foo invalid and can't use -1 because foo can be negative. I still don't want to bother the compiler by changing the type. Both Infinity and NaN satisfy typeof === 'number', so I could use either? Are there any pitfalls with either?

Example: NaN != NaN (but there is Number.isNaN), but Infinity === Infinity.

I need to check whether the new number equals the old foo, so I would use NaN because it's shorter while semantically in my code both make sense.

Edit: Usage is to determine whether the cached value is still valid. (Note the original is written in Coffeescript.)

someCachedGetter: (() => {
  let foo = NaN; let cache = null;
  return () => {
    let t = getFoo();
    if (foo === t) { return cache; }
    else { foo = t; return cache = expensiveOperation(); }
}})(),
0 Answers
Related