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?
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?
3 Answers
Reset to default 12are 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
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
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.
price
is. Try withvar price = {valueOf() { throw new Error; }}
– Bergi Commented Oct 31, 2016 at 10:59