JavaScript Type Conversion
JavaScript often converts values from one type to another automatically, called type coercion — for example, `'5' + 1` produces `'51'` because + triggers string concatenation.
You can also convert types explicitly using functions like `String()`, `Number()`, and `Boolean()`, which is safer and clearer than relying on implicit coercion.
Implicit coercion
`+` with a string operand converts everything to strings, while `-`, `*`, `/` try to convert operands to numbers. This can cause surprising results like `'5' - 1` being `4` but `'5' + 1` being `'51'`.
Explicit conversion
`Number('42')` gives 42, `String(42)` gives '42', and `Boolean(1)` gives true — always predictable and easy to read.
console.log("5" + 1);
console.log("5" - 1);51
4+ concatenates when a string is involved; - coerces to numbers.
console.log(Number("42"));
console.log(String(42));
console.log(Boolean(""));42
42
falseExplicit conversion functions make the intended type change obvious.
Key points
- + concatenates strings; other math operators coerce to numbers.
- Number(), String(), Boolean() perform explicit conversion.
- Implicit coercion can cause confusing bugs — be cautious with +.
- Number('abc') returns NaN, since 'abc' isn't numeric.
