JavaScript: Identify Not-a-Number Values
In JavaScript, NaN (Not-a-Number) is a special value that represents an unrepresentable numerical result. Understanding how to reliably detect NaN is crucial for robust data validation and error handling, especially when dealing with user input or results from mathematical operations that might fail. This challenge will test your ability to correctly distinguish NaN from other numerical types.
Problem Description
Your task is to write a JavaScript function that accepts a single argument and returns true if the argument is NaN, and false otherwise.
Key Requirements:
- The function should correctly identify
NaNregardless of how it is obtained (e.g.,NaN,0/0,parseInt("hello")). - The function should return
falsefor all other JavaScript primitive types and common object types.
Expected Behavior:
- If the input is
NaN, the function must returntrue. - If the input is any other number (including
Infinity,-Infinity,0,-0), a string, a boolean,null,undefined, an object, an array, or a function, the function must returnfalse.
Edge Cases to Consider:
NaNis unique in thatNaN === NaNevaluates tofalse. Your solution must account for this.- Inputs like
Infinityand-Infinityare numbers but notNaN.
Examples
Example 1:
Input: NaN
Output: true
Explanation: The input is the literal NaN value.
Example 2:
Input: 0 / 0
Output: true
Explanation: Division of zero by zero results in NaN.
Example 3:
Input: parseInt("hello")
Output: true
Explanation: Attempting to parse a non-numeric string with parseInt results in NaN.
Example 4:
Input: 123
Output: false
Explanation: 123 is a standard number.
Example 5:
Input: Infinity
Output: false
Explanation: Infinity is a numeric value, but not NaN.
Example 6:
Input: "hello"
Output: false
Explanation: "hello" is a string, not NaN.
Example 7:
Input: null
Output: false
Explanation: null is a primitive type but not NaN.
Example 8:
Input: undefined
Output: false
Explanation: undefined is a primitive type but not NaN.
Constraints
- The function will be called with a single argument.
- The argument can be any valid JavaScript data type.
- Performance is not a critical concern for this specific challenge, but efficiency is always good practice.
Notes
Consider the peculiar nature of NaN's equality comparison. There are built-in JavaScript methods designed for this exact purpose, as well as ways to leverage its unique properties.