Type Conversion
JavaScript quietly converts values between types — sometimes helpfully, often surprisingly. Learn the rules and you avoid a whole family of bugs.
On this page · 5 min · Beginner
On this page
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 27, 2026
Learning objectives#
- Predict implicit coercion with + and −
- Convert explicitly with Number, String and Boolean
- Parse numbers from text with parseInt and parseFloat
- Detect invalid numbers with Number.isNaN
Explanation#
Implicit coercion: if either side of + is a string, JavaScript joins strings ("5" + 2 → "52"). Other maths operators convert to numbers ("5" - 2 → 3).
Explicit conversion is clearer: Number("42") → 42, String(99) → "99", Boolean("") → false.
Number() is strict: Number("42px") is NaN (Not a Number). parseInt("42px") reads digits until it hits a non-digit and returns 42.
Form inputs always give you strings. Convert them before doing maths.
Code example: Coercion surprises and explicit conversion#
console.log('5' + 2);
console.log('5' - 2);
console.log(Number('42'), Number('42px'), parseInt('42px'));
console.log(String(99) + 1);
console.log(Boolean(''), Boolean('0'), Boolean(0));
console.log(Number.isNaN(Number('abc')));
52 3 42 NaN 42 991 false true false true
Step-by-step explanation#
- "5" + 2: + with a string joins → "52".
- "5" - 2: minus only works on numbers, so "5" becomes 5 → 3.
- Number("42px") fails → NaN, but parseInt reads "42".
- Boolean("0") is true — any non-empty string is truthy, even "0".
- Number.isNaN reliably checks for NaN.
Real-world use case#
A quantity box on a shop page returns "2". Without Number(), "2" + 1 becomes "21" and your cart total is wrong.
Common mistakes#
input.value is always a string. Use Number(input.value) or input.valueAsNumber before adding.
NaN === NaN is false! Use Number.isNaN(value).
Best practices#
- Convert explicitly instead of relying on coercion
- Use Number() for strict conversion and parseInt(str, 10) when text has units
- Always validate converted numbers with Number.isNaN
- Use === so comparisons never coerce
Remember this#
String + anything = string. Minus, times, divide = number.
NaN is the only value not equal to itself — test it with Number.isNaN().
Inputs give strings. Convert before you calculate.
Practice exercise#
Your task: Two inputs gave "250" and "3". Calculate and print the total cost (250 × 3) and the sum (253) correctly.
Show solution
const price = '250', qty = '3';
console.log(Number(price) * Number(qty)); // 750
console.log(Number(price) + Number(qty)); // 253
Mini quiz#
What does this print?
console.log('10' - '4' + '1');
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.