In the codebase I'm working on, I encountered code like this:
try {
price = parseFloat(price);
} catch (err) {
console.log(err);
}
I know that in most cases where price
cannot be turned into a number, it'll simply get the value of NaN
instead. My question is: are there cases where it will throw an error, making the try-catch-construction necessary?
are there cases where it will throw an error, making the try-catch-construction necessary?
Yes. Apart from reference errors (because price
was not declared) or parseFloat
was overwritten with something that's not a function or the like, the builtin parseFloat
can also throw exceptions.
It does however never throw an error when you pass in a string. It will only throw when trying to convert the argument to a string fails with an exception. Examples for that include:
[Symbol.toPrimitive]
, .valueOf
or .toString
methodsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With