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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn 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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more