When providing JavaScript’s parseInt
with a non-parsable string it returns NaN
. I’m trying to understand the reasons for designing a parsing function this way.
When I write a parsing function I usually return null
or throw an exception in case the input is not parsable. It seems to me that NaN
is unsafe because it allows the code to keep running even when there is no value to work with.
For example, this will not throw any runtime error:
parseInt('a') + 1
But this could lead to unexpected behavior when you expect something to be an actual number while it’s actually NaN
.
So my question is: Shouldn’t such a parsing function just return null
or throw an exception, or are there benefits to returning NaN
instead?