Hone logo
Hone
Problems

Is It Really a Number? Validating Numeric Values in JavaScript

Determining if a value is a number in JavaScript can be surprisingly tricky due to the language's type coercion. This challenge asks you to write a function that accurately identifies whether a given value represents a valid number, accounting for various input types and potential pitfalls. This is a common task in data validation and user input handling.

Problem Description

You are tasked with creating a JavaScript function called isNumeric that takes a single argument, value, and returns true if the value is a valid number, and false otherwise. A "valid number" in this context means:

  • It's a number primitive (e.g., 10, 3.14, -5).
  • It's a string that can be successfully parsed into a number (e.g., "10", "3.14", "-5").
  • It's NaN (Not a Number).
  • It's Infinity or -Infinity.

The function should return false for the following:

  • null
  • undefined
  • Empty string ("")
  • Strings that cannot be parsed into numbers (e.g., "abc", "10a")
  • Objects
  • Arrays
  • Booleans
  • Functions

Examples

Example 1:

Input: 10
Output: true
Explanation: The input is a number primitive.

Example 2:

Input: "3.14"
Output: true
Explanation: The input is a string that can be successfully parsed into a number.

Example 3:

Input: "abc"
Output: false
Explanation: The input is a string that cannot be parsed into a number.

Example 4:

Input: null
Output: false
Explanation: The input is null.

Example 5:

Input: NaN
Output: true
Explanation: The input is NaN.

Example 6:

Input: Infinity
Output: true
Explanation: The input is Infinity.

Example 7:

Input: [1, 2, 3]
Output: false
Explanation: The input is an array.

Constraints

  • The input value can be of any JavaScript data type.
  • The function must handle all edge cases described in the Problem Description.
  • The function should be reasonably efficient; avoid unnecessary iterations or complex operations.
  • The function should not modify the input value.

Notes

  • Consider using the typeof operator and the Number() constructor for type checking and conversion.
  • Be mindful of JavaScript's type coercion rules. Number("10") is different from 10.
  • The isNaN() function can be useful, but be aware of its quirks (it coerces its argument to a number first). Number.isNaN() is a more reliable alternative for checking if a value is actually NaN.
  • Think about how to handle strings that contain non-numeric characters.
Loading editor...
javascript