Skip to the solution
MediumFrontend6 min read

How do you correctly check for NaN?

953 views

The problem

Question presented to candidate: "isNaN('hello') returns true. Does that mean the string 'hello' actually IS NaN? What's really happening there, and what should you use instead?"

What a strong answer should cover:

  • πŸ“Œ Interview term: NaN === NaN is false β€” the famous, real starting trap: NaN is the one value in JavaScript that is genuinely never equal to itself under ===, so equality comparison alone can never detect it.
  • πŸ“Œ Interview term: the global isNaN() β€” verified directly: it genuinely coerces its argument to a number FIRST, then checks if the coerced result is NaN β€” this is exactly why isNaN("hello") is true: "hello" isn't literally the value NaN, it just genuinely FAILS numeric coercion, producing NaN, which the global function then reports.
  • πŸ“Œ Interview term: the real, direct answer to the prompt β€” verified directly: "hello" is genuinely not NaN itself; isNaN("hello") being true is a real, misleading side effect of coercion, not a report that the string literally holds the value NaN. Number.isNaN("hello") β€” the correct, precise check β€” genuinely does NOT coerce at all, correctly returning false.
  • πŸ“Œ Interview term: Number.isNaN() β€” verified directly: it only returns true for the value that is LITERALLY NaN (including the real result of 0/0) β€” no coercion, no false positives for non-numeric strings.
  • A precise answer names Object.is(x, NaN) as a real, valid alternative producing the identical correct result to Number.isNaN(x), since Object.is (unlike ===) is specifically defined to treat NaN as equal to itself.

Clarifying questions expected:

  • None β€” this is a definitional/technical question; directly answering WHY isNaN("hello") is misleadingly true (coercion, not literal NaN) is the strong signal.

Code / implementation expected: Yes β€” the direct side-by-side isNaN() vs. Number.isNaN() comparison on the exact same inputs is the clearest, most convincing demonstration.

  • nan

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal proof: the global isNaN() coerces first (giving a misleading true for 'hello'), while Number.isNaN() correctly does not coerce

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 56 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are modules in JavaScript?

Continue