Skip to curriculum
Jump to the editor

1.5. Detect NaN and integers

Easy
Topics
10–15 min

Numbers from forms, URLs and JSON are often not what they seem: Number("abc") is NaN, 0.1 + 0.2 is not a whole number, and an id larger than 2 ** 53 silently changes when it is parsed. JavaScript has built-in checks for these cases, and the older ones convert their argument first, so the global isNaN("abc") is true. Writing the checks yourself shows exactly what each one must rule out.

Write three functions in numbers.js: isNaNValue, isInteger and isSafeInteger.

Signature

JAVASCRIPT
function isNaNValue(value)    // boolean
function isInteger(value)     // boolean
function isSafeInteger(value) // boolean

Requirements

  1. isNaNValue(value) is true for the number value NaN, however it was produced (0 / 0, Number("abc"), Math.sqrt(-1)).
  2. isNaNValue never converts its argument: strings, undefined, objects and a Number object holding NaN all give false, and so do ordinary numbers and the infinities.
  3. isInteger(value) is true for a number primitive with no fractional part: 0, -0, negative numbers, and very large numbers such as 2 ** 53 and 1e21.
  4. isInteger is false for numbers with a fraction, for NaN, Infinity and -Infinity, and for anything that is not a number primitive ("5", true, null, [5], new Number(5), 5n).
  5. isSafeInteger(value) is true for integers from -(2 ** 53 - 1) to 2 ** 53 - 1, both ends included, and false for everything else.
  6. All three return true or false, never another value.

Examples

JAVASCRIPT
isNaNValue(NaN);         // true
isNaNValue("abc");       // false (the global isNaN says true)
isNaNValue(undefined);   // false
JAVASCRIPT
isInteger(5);            // true
isInteger(5.5);          // false
isInteger(Infinity);     // false
isInteger("5");          // false
isInteger(2 ** 53);      // true
JAVASCRIPT
isSafeInteger(2 ** 53 - 1); // true
isSafeInteger(2 ** 53);     // false

Environment

  • Plain JavaScript in a browser page; the tests call the three globals from numbers.js.
  • Not allowed: Number.isNaN, the global isNaN, Number.isInteger and Number.isSafeInteger. The tests replace them with functions that throw. Everything else, including Number.isFinite, Math and Number.MAX_SAFE_INTEGER, may be used.

Hints

  1. Which value is not equal to itself?
  2. Math.trunc(Infinity) is Infinity. What else must an integer be, besides "unchanged by Math.trunc"?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…