Skip to content
Exercise · Operators and type conversion · lesson 14 of 14

Exercise: a number or a fallback

Write a function function toNumberOr(text, fallback) that returns Number(text), or the value fallback if that is NaN.

  • toNumberOr("42", 0) → 42
  • toNumberOr("12px", -1) → -1
  • toNumberOr("0", 7) → 0

Constraints: text is a string, possibly empty (it gives 0, as in Number); fallback is any number, including 0.

Do not add extra imports unless the task says so explicitly.

number.js — javascript
javascript · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way