JavaScript: Is It a Number?
In JavaScript, determining if a value is a number can be surprisingly nuanced due to its dynamic typing. This challenge will test your ability to correctly identify various numeric types and handle potential pitfalls, ensuring your code behaves predictably.
Problem Description
You need to create a JavaScript function called isNumber that accepts a single argument, value. This function should return true if the value is a valid number and false otherwise.
Key Requirements:
- The function must distinguish between actual numbers and other data types like strings, booleans, null, undefined, objects, and arrays.
- It should correctly identify primitive numbers (e.g.,
10,3.14,-5). - It should also correctly identify the special numeric value
Infinityand-Infinity. - It must not consider
NaN(Not-a-Number) as a valid number for this challenge. - The function should handle potential type coercion implicitly and correctly.
Expected Behavior:
- If
valueis a primitive number or a Number object representing a finite number or infinity, returntrue. - If
valueisNaN, returnfalse. - If
valueis any other data type (string, boolean, null, undefined, object, array, etc.), returnfalse.
Edge Cases to Consider:
NaNInfinityand-Infinity- Strings that look like numbers (e.g.,
"123") nullandundefined
Examples
Example 1:
Input: 123
Output: true
Explanation: 123 is a primitive number.
Example 2:
Input: "hello"
Output: false
Explanation: "hello" is a string, not a number.
Example 3:
Input: NaN
Output: false
Explanation: NaN is a special numeric value but is explicitly excluded as a valid number for this challenge.
Example 4:
Input: Infinity
Output: true
Explanation: Infinity is considered a valid numeric value in JavaScript.
Example 5:
Input: null
Output: false
Explanation: null is not a number.
Example 6:
Input: [1, 2, 3]
Output: false
Explanation: An array is not a number.
Example 7:
Input: "42.5"
Output: false
Explanation: Although this string *represents* a number, the function should only return true for actual numeric types.
Constraints
- The input
valuecan be of any JavaScript data type. - The function must be written in plain JavaScript, without relying on external libraries.
- The solution should be efficient and have a time complexity of O(1).
Notes
Consider the built-in JavaScript methods available for type checking and number manipulation. Think about how different numeric representations (like new Number(5)) should be handled. Remember that typeof can be misleading in some scenarios when checking for numbers.