A Weird Thing with NaN
At work we encountered a problem with NaN
. For those who do not know, NaN
stands for not-a-number. It represents when a computer cannot get a number from a mathematical operation.
Here are some different situations with JavaScript that can result in NaN
:
- Creating a number too big for the computer.
- Dividing a number by a string.
- Failing to convert a string to a number.
- Doing an operation with
NaN
.
Okay, back to the bug.
We were trying to validate some user input. The input comes from a URL query, which can look like this:
example.com/search?q=123
The query comes into our system as a string, even if it only contains digits. For those that do not know, a string is just something that represents text. Digits can be formatted as a number or string. 123
would be a number and "123"
would be a string. They are not equal to each other.
Later in the system we try to convert the input to a number. And then check if it is actually a number. But this check wasn’t working, it was always returning true. Even for inputs like "hello there"
which is clearly not a number.
let input = "hello there";
let value = Number(input);
if (typeof value === "number")…