Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does parseFloat ever throw an error?

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?

like image 830
Bart S Avatar asked Dec 18 '22 12:12

Bart S


1 Answers

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:

  • passing a symbol
  • passing an object without [Symbol.toPrimitive], .valueOf or .toString methods
  • passing an object where one of these methods throws
  • passing an object where none of these methods return a primitive
like image 63
Bergi Avatar answered Dec 30 '22 17:12

Bergi