JS-Dev-101 practice question 7 of 25

Given a value, which two options can a developer use to detect if the value is NaN?

Full set: 148 questions
Answer options
A: value === Number.NaN
B: value == NaN
C: isNaN(value) Correct answer
D: Object.is(value, NaN) Correct answer
Correct Answer:
C. isNaN(value); D. Object.is(value, NaN)
Explanation

In JavaScript, NaN (Not-a-Number) has the unique property of not being equal to itself, so direct comparison (== or ===) fails. The global isNaN() function correctly identifies NaN, but it has a notable quirk: it coerces its argument to a number, so isNaN('hello') returns true. A more robust and modern method is Object.is(value, NaN), introduced in ES2015 (ES6). It determines if two values are the same without type coercion and correctly identifies NaN without the side effects of the global isNaN() function.

Why Incorrect

A. value === Number.NaN will always evaluate to false because NaN is never strictly equal to itself or any other value.
B. value == NaN will always evaluate to false because NaN is never loosely equal to itself or any other value.

References

1. ECMA-262, 11th Edition. (June 2020). ECMAScript® 2020 Language Specification. Section 7.2.14, "SameValueZero(x, y)" and Section 20.1.2.12, "Object.is ( value1, value2 )". (The specification details why Object.is(NaN, NaN) is true).

2. MDN Web Docs. (2023). NaN. Mozilla. Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/NaN. (Section: "Testing against NaN").

3. MDN Web Docs. (2023). Object.is(). Mozilla. Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/Object/is. (Section: "Description" and "Examples").

4. Haverbeke, M. (2018). Eloquent JavaScript (3rd ed.). No Starch Press. Chapter 1, "Values, Types, and Operators," Section "Special numbers".

Scroll to Top