Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Sanket Patel
Sanket Patel

Posted on

     

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

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

functionformattedAmount(x){if(isNaN(x)){return"Not a Number!";}return"$"+x.toFixed(2);}console.log(formattedAmount(""));// output: Error: x.toFixed is not a functionconsole.log(formattedAmount(null));// output: Error: Cannot read property 'toFixed' of null
Enter fullscreen modeExit fullscreen mode

This can be fixed usingNumber() function or+ operator. It will createNumber object of variablex. Hence both empty string andnull will result into number0 and accordingly, rest of the statement will be executed.

functionformattedAmount(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 modeExit fullscreen mode

Hope you find it useful.

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

Proofread by@ron4ex

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
robotmayo profile image
Robotmayo
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Parenting, Coding, Traveling| Co-owner @ https://redsoftware.in/| Maintainer @ https://github.com/reactjs/gu.reactjs.org
  • Location
    Surat, Gujarat, India
  • Joined

More fromSanket Patel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp