Technical skill practice

Convert a String to a Number in JavaScript: Reject Invalid Counts

Converting text to a number is separate from deciding whether it is a valid count. Number reads the whole numeric input, while parseInt can accept an initial integer portion. Check the result against the rule your application actually needs.

The task

Accept only nonblank text that converts to a finite, nonnegative integer. This small contract permits surrounding whitespace and leading zeroes; it does not accept partial units such as “12boxes.”

Runnable Node 22 example

const assert = require('node:assert/strict');

function countFromText(text) {
  if (typeof text !== 'string' || text.trim() === '') return null;
  const value = Number(text);
  return Number.isFinite(value) && Number.isInteger(value) && value >= 0 ? value : null;
}
assert.equal(Number(''), 0);
assert.equal(parseInt('12boxes', 10), 12);
assert.equal(Number.isNaN(Number('12boxes')), true);
assert.equal(countFromText(' 007 '), 7);
assert.equal(countFromText(''), null);
assert.equal(countFromText('12boxes'), null);
assert.equal(countFromText('-2'), null);
assert.equal(countFromText('2.5'), null);
assert.equal(countFromText('Infinity'), null);
console.log(JSON.stringify([' 007 ', '', '12boxes'].map(countFromText)));

Expected output and explanation

The first two assertions expose conversion shortcuts that would be unsuitable for this count rule: blank text becomes zero through Number, and partial text becomes twelve through parseInt. The guard rejects blank text before conversion and then checks the numeric properties explicitly.

Null is the function’s chosen invalid-result marker, so a legitimate zero remains distinguishable from failure. A different application might need decimal values, reject exponent notation or impose a maximum safe size. Add those rules deliberately instead of assuming numeric conversion validates the entire business input.

Output from the example

[7,null,null]

Pitfall to check

Number.isInteger alone does not reject every value outside a practical count range. If counts can grow large, define a range and consider Number.isSafeInteger. Do not treat a parsed value as permission to allocate that many items without bounds.

Questions, answered

Is parseInt always wrong for numeric text?

No. It is useful when accepting a leading integer is the intended operation. It does not enforce the whole-string contract used by this example.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.