Module 2: Language Fundamentals
Type Conversion and Coercion
Distinguish intentional conversion from automatic type coercion.
Type conversion changes a value from one type to another. Explicit conversion is usually clearer than relying on implicit coercion.
const input = "42";
const count = Number(input);
console.log(count + 8); // 50
console.log(String(25)); // "25"
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
A conversion may fail to produce the value you expect. Number("hello") gives NaN (Not-a-Number), so validate numeric input with Number.isNaN or Number.isFinite after conversion.
Implicit coercion#
The + operator can concatenate strings or add numbers. If either operand becomes a string, the result may be concatenation:
console.log("5" + 1); // "51"
console.log("5" - 1); // 4
console.log(2 * "3"); // 6
These rules can surprise readers. Convert values at application boundaries, such as when receiving form input or parsing query parameters, and validate them before calculations.
Equality#
=== compares without coercing operand types first and is the preferred default. == applies coercion rules, which are sometimes useful but often confusing to beginners.
console.log(5 === "5"); // false
console.log(5 == "5"); // true
Practice#
Read a string from a hypothetical form, convert it to a number, reject empty or invalid input, and only then calculate a total.