Basics
String → number: Number(), parseInt(), parseFloat()
Number is a strict conversion; parseInt "pulls a number off the front of a string".
Why it exists
Everything that comes from the outside world is text: form fields, URL parameters, CSV, headers, localStorage. You can't compute with text: "5" + 1 is "51". Before calculating, the string has to become a number, and there are several ways — each behaving differently on "dirty" data. Your choice decides whether junk becomes an error or a plausible but wrong number.
Where it's used
- Form fields:
Number(input.value). - URL parameters:
Number(searchParams.get("page") ?? 1). - CSS values:
parseFloat("12.5px")→12.5. - Printing a number as text:
String(count)or a template string.
Syntax
Number(string)
parseInt(string, 10)
parseFloat(string)
String(number)Examples
Number("42"); // → 42
Number("42px"); // → NaN
parseInt("42px", 10); // → 42Number(""); // → 0
Number(" "); // → 0
Number("12.5"); // → 12.5parseInt("12.9", 10); // → 12
parseFloat("12.9kg"); // → 12.9
parseInt("abc", 10); // → NaNparseInt and parseFloat read the start of the string"5" + 1; // → "51"
Number("5") + 1; // → 6Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
`Number(s)` requires the whole string (ignoring spaces around it) to be a number: "42", " 3.5 ", "-7", "1e3". Extra characters give NaN. Special cases: an empty string and a string of spaces give 0; Number(null) is 0, Number(undefined) is NaN, Number(true) is 1.
`parseInt(s, 10)` skips leading spaces, reads digits while they last, and stops at the first "foreign" character. The rest is silently dropped: "42abc" → 42, "12.9" → 12. If there are no digits at the start, it's NaN. The second argument is the base; write 10.
`parseFloat(s)` is the same but understands a fractional part: "12.5px" → 12.5.
The unary plus +s works like Number(s).
Checking the result: Number.isNaN(x) — "is it not a number", Number.isInteger(x) — "is it whole", Number.isFinite(x) — "is it an ordinary finite number".
Traps
How it differs from…
Number.isInteger()After converting, Number.isInteger checks that the result is a whole number — and rules out
NaNalong the way.- Joining strings
+with a string joins rather than adds: if either side is a string, the result is a string.
When to pick something else
Don't use parseInt to check that the user typed a number — it quietly accepts "42abc". And don't convert what's already a number: JSON.parse and response.json() return numbers on their own.