JavaScript type conversion transforms values between strings, numbers, and booleans either explicitly through functions you call or implicitly when operators mix types. Explicit conversion makes your intent obvious and eliminates subtle coercion bugs.
Use these three clean built-in functions whenever reading form inputs, URL query strings, or environment flags:
Number(val): Converts numeric strings ("42.5" -> 42.5), booleans (true -> 1, false -> 0), and returns NaN for invalid text like "12px".String(val): Safely converts any value—including null and undefined—into a readable string ("null", "undefined").Boolean(val): Converts any value into true or false based on truthy/falsy rules.The + operator behaves differently from -, *, and /: if either operand is a string, + concatenates text instead of doing math.
const formInput = "25";
const quantity = Number(formInput); // Explicit conversion
if (!Number.isNaN(quantity)) {
console.log("Total:", quantity + 5); // 30 (not "255"!)
}
// Watch out for implicit + vs - coercion
console.log("'5' + 2 =", "5" + 2); // "52" (string concatenation)
console.log("'5' - 2 =", "5" - 2); // 3 (numeric subtraction)
// Safe boolean parsing for query strings ("false" is truthy!)
const queryFlag = "false";
const isEnabled = queryFlag === "true";
console.log("Parsed flag:", isEnabled); // false
Boolean("false") to parse flags: Because "false" is a non-empty string, Boolean("false") returns true! Compare str === "true" instead.Number("") equals 0: Empty strings and whitespace-only strings convert to 0 under Number(). Trim and check for "" before parsing optional numbers.val.toString() on nullable values: Calling .toString() on null or undefined crashes with a TypeError. Use String(val) instead.Number(x) and +x?Both convert x into a number identically, except Number(x) is self-documenting for teammates while unary +x is easy to miss or misread as addition.
parseInt() differ from Number()?Number.parseInt("42px", 10) stops at "p" and returns 42, whereas Number("42px") rejects the trailing letters and returns NaN.
Pass the millisecond number to new Date(timestamp).toISOString().
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.