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
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"
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)
For further actions, you may consider blocking this person and/orreporting abuse