Explain Codes LogoExplain Codes Logo

How to turn NaN from parseInt into 0 for an empty string?

javascript
parseint
number
javascript-best-practices
Anton ShumikhinbyAnton Shumikhin·Dec 7, 2024
TLDR

Deal with parseInt handing you NaN when given an empty string by using the nullish coalescing operator (??):

const result = parseInt('') ?? 0; console.log(result); // Logs 0, but NaN isn't invited

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:

const result = Number(''); console.log(result); // 0, happy days tomorrow

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:

const result = (parseInt('') | 0); console.log(result); // 0, even for NaN, take that!

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:

function parseToIntOrZero(str) { const parsed = parseInt(str); return isNaN(parsed) ? 0 : parsed; // Be the change(NaN) you want to see in the world }

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:

const number = parseInt(s) || 0; // Redirects 0 to a wrong turn const safeNumber = Number(s) || 0; // Okay Google, take me home

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.