How to turn NaN from parseInt into 0 for an empty string?
Deal with parseInt
handing you NaN when given an empty string by using the nullish coalescing operator (??
):
The ??
operator specifically checks for null
or undefined
, ensuring they don't crash the party. It doesn't replace other falsy values like 0
, so no awkward silences at the networking event.
Lean on the robustness of Number()
Number()
converts strings to numbers sans dramatics and treats empty strings as 0
:
Number()
avoids the decimal-to-binary conundrums that parseInt
thrusts upon us.
Bitwise OR: Punchy, Yet Opinionated
For syntax that's short and sweet but may confound the uninitiated, try bitwise OR:
A caveat: this method insists on an int. It's the TypeScript
in a world of JavaScript
.
Customize with a Helper Function
For reusable and consistent NaN
handling, consider a bespoke helper function:
Handy in multiple zones of your app. Maximum impact, minimum effort!
Quirks of Implicit Conversion and Conditionals
Understanding the falsiness of 0
is crucial, especially when coding conditional checks:
Rely on the Number() constructor or bitwise OR to treat 0
as a true value.
Fathom the 'why' of Parsing
Ask yourself:
- Do I covet integer precision?
- Must spaces within strings become passe?
- What's my stance on input validation?
Choose the method that best fits into your project's requirements.
Was this article helpful?