6

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?

Bart S
  • 1,698
  • 1
  • 16
  • 21

3 Answers3

12

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
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Short answer: No.

from MDN

A floating point number parsed from the given string. If the first character cannot be converted to a number, NaN is returned

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

Felipe Sabino
  • 17,825
  • 6
  • 78
  • 112
  • It can still fail with an error message if the variable does not exist. And OP explicitly asks if there are cases when the try/catch is necessary when using `parseFloat()`. – kb. Oct 31 '16 at 10:56
0

parseFloat() itself only returns and never throws an error. However if the variable price has not been declared in the context you will get an error like:

Uncaught ReferenceError: price is not defined

It explains the reason why there is a try/catch block around it.

So to answer your question: Yes there are cases when it is necessary if you can't trust previous js execution/context (due to adblockers or similar for instance) but no it's not the function parseFloat() that throws the error it's the interpreter.

kb.
  • 1,955
  • 16
  • 22
  • 2
    That error has nothing to do with `parseFloat` though, it's thrown (by trying to read an undeclared variable) before it even reaches `parseFloat`. – Quentin Oct 31 '16 at 10:56
  • @quentin Correct, so I clarified that. But if you read the actual question, not just the title, OP says *My question is: are there cases where it will throw an error, making the try-catch-construction necessary?* and my answers explains that whereas saying "No, parseFloat() can't give an error" is misleading in the context of the question. So please retract your downvote, this is the answer to OP's question. – kb. Oct 31 '16 at 10:58