DEV Community

Sanket Patel
Sanket Patel

Posted on

2

isNaN('') = false 😅, how to handle it?

I recently noticed that isNaN('') and isNaN(null) both return false in JavaScript. It means that both empty string and null are valid numbers. So if you want to perform any number specific operation by just comparing the variable using isNaN(), it won't work. Here is an example:

function formattedAmount(x) {
  if (isNaN(x)) {
    return "Not a Number!";
  }
  return "$ " + x.toFixed(2);
}

console.log(formattedAmount(""));
// output: Error: x.toFixed is not a function

console.log(formattedAmount(null));
// output: Error: Cannot read property 'toFixed' of null
Enter fullscreen mode Exit fullscreen mode

This can be fixed using Number() function or + operator. It will create Number object of variable x. Hence both empty string and null will result into number 0 and accordingly, rest of the statement will be executed.

function formattedAmount(x) {
  if (isNaN(x)) {
    return "Not a Number!";
  }
  return "$ " + Number(x).toFixed(2);
  // OR
  // return '$ '+ (+x).toFixed(2);
}

console.log(formattedAmount(""));
// output: "$ 0.00"

console.log(formattedAmount(null));
// output: "$ 0.00"

console.log(formattedAmount(12.126));
// output: "$ 12.13"
Enter fullscreen mode Exit fullscreen mode

Hope you find it useful.

I made a quick check but didn't get why exactly in JavaScript isNaN('') is false. I would love to know if you have anything to say regarding that. Thanks for reading!

Proofread by @ron4ex

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (2)

Collapse
 
robotmayo profile image
Robotmayo •

Whats happening is you are misunderstanding what isNaN does. It does not check if the value passed is or isn't a number, it only check if the value is the global constant NaN

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up