Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Parse Number or Null

Fundamentals: Part 1easy

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 11: Data Types

Implement `toNumber(str)` returning the numeric value of `str`, or `null` when it is not a valid number.

Sample tests

Input: toNumber("42")
Output: 42
Input: toNumber("3.14")
Output: 3.14

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • NaN === NaN is false, so compare with Number.isNaN, not ===.
  • Number('') is 0, not NaN, which may surprise you.

Learning resources

  • MDN: typeof
Approach & explanation (try first)

Number() does the coercion and Number.isNaN reliably detects the failure case so you can return null instead of NaN.

Loading...
⌘/Ctrl + Enter

Run your code to see results.