Type Coercion
Type Coercion
Section titled βType CoercionβWhat it means
Section titled βWhat it meansβ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)).
Examples
Section titled βExamplesβconsole.log("5" + 3); // "53" -- number coerced to string, then concatenatedconsole.log("5" - 3); // 2 -- string coerced to number for subtractionconsole.log("5" * "2"); // 10 -- both coerced to numbersconsole.log(1 + true); // 2 -- true coerces to 1console.log("5" + true); // "5true" -- true coerces to the string "true"
// Explicit conversion (preferred when the intent matters)console.log(Number("42")); // 42console.log(String(42)); // "42"console.log(Boolean("")); // falseconsole.log(parseInt("42px", 10)); // 42 -- stops at the first non-digitCommon mistake
Section titled βCommon mistakeβ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 combiningfunction total(price, quantity) { return Number(price) + Number(quantity);}total("10", 3); // 13 -- correctQuick practice
Section titled βQuick practiceβ-
What does
"5" + 3evaluate 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. -
What does
"5" - 3evaluate to, and why is it different from+?Answer
2β unlike+,-has no string-concatenation meaning, so JavaScript coerces the string to a number and subtracts. -
Whatβs the safer alternative to relying on implicit coercion when combining user input with numbers?
Answer
Explicit conversion withNumber()(orparseInt()/parseFloat()) before doing arithmetic, so the intent is clear and unexpected string concatenation is avoided.