JavaScript Explicit Type Conversion
Quick answer
Explicit conversion requests a particular type through operations such as Number(value), String(value) or Boolean(value). The result follows language conversion rules, not necessarily an application’s idea of valid input.
How it works
Number converts a complete numeric string after permitted whitespace handling. Empty or whitespace-only strings convert to zero; invalid numeric text gives NaN. Number(null) is zero and Number(undefined) is NaN. String returns a text representation; Boolean uses truthiness. Number.isNaN tests whether an actual Number value is NaN without coercing its input.
console.log(Number(" 18 "));console.log(Number(""));console.log(Number.isNaN(Number("18px")));Expected output in Node.js:
180trueThe whole string must be numeric; px makes it invalid.
console.log(String(25) + " units");console.log(Boolean("0"));console.log(Number(null));Expected output in Node.js:
25 unitstrue0Each conversion has its own rules.
Common mistakes
Do not treat successful Number conversion as proof of valid business input: an empty field becomes zero. Avoid relying on String for object serialization. Do not use Number on arbitrary large BigInt values when exactness is required.
Practice
Given a numeric decimal string within a stated bounded contract, convert it to a number and add a fixed service fee.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Explicit Type Conversion — Knowledge Check
Apply the taught concept and reason about the result.
What does Number(" 42 ") return?
What does Number("") return?
What does Number.isNaN(Number("12px")) return?
What does String(15) return?
Why should an empty form field be checked before Number conversion?