Skip to content

Type Coercion

Type coercion is JavaScript automatically converting a value from one type to another β€” usually to make an operator work despite mismatched operand types. It happens implicitly (JavaScript decides for you, e.g. with + or ==) or explicitly (you request the conversion yourself, e.g. Number(x) or String(x)).

console.log("5" + 3); // "53" -- number coerced to string, then concatenated
console.log("5" - 3); // 2 -- string coerced to number for subtraction
console.log("5" * "2"); // 10 -- both coerced to numbers
console.log(1 + true); // 2 -- true coerces to 1
console.log("5" + true); // "5true" -- true coerces to the string "true"
// Explicit conversion (preferred when the intent matters)
console.log(Number("42")); // 42
console.log(String(42)); // "42"
console.log(Boolean("")); // false
console.log(parseInt("42px", 10)); // 42 -- stops at the first non-digit

Using + expecting numeric addition when one operand is a string β€” + is the one arithmetic operator that also means string concatenation, so it silently does the β€œwrong” thing instead of throwing an error.

function total(price, quantity) {
return price + quantity;
}
total("10", 3); // "103" -- string concatenation, not 13!
// Fix: convert explicitly before combining
function total(price, quantity) {
return Number(price) + Number(quantity);
}
total("10", 3); // 13 -- correct
  1. What does "5" + 3 evaluate to, and why?

    Answer"53" β€” when either operand of + is a string, JavaScript coerces the other operand to a string too and concatenates, rather than adding numerically.
  2. What does "5" - 3 evaluate to, and why is it different from +?

    Answer2 β€” unlike +, - has no string-concatenation meaning, so JavaScript coerces the string to a number and subtracts.
  3. What’s the safer alternative to relying on implicit coercion when combining user input with numbers?

    AnswerExplicit conversion with Number() (or parseInt()/parseFloat()) before doing arithmetic, so the intent is clear and unexpected string concatenation is avoided.