JS Type Conversion
JavaScript Type Conversion: Explicit Casting vs. Implicit Coercion
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.
Explicit Conversion Functions
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 returnsNaNfor invalid text like"12px".String(val): Safely converts any value—includingnullandundefined—into a readable string ("null","undefined").Boolean(val): Converts any value intotrueorfalsebased on truthy/falsy rules.
Implicit Coercion Pitfalls vs. Explicit Code
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
Common Mistakes to Avoid
- Using
Boolean("false")to parse flags: Because"false"is a non-empty string,Boolean("false")returnstrue! Comparestr === "true"instead. - Forgetting
Number("")equals0: Empty strings and whitespace-only strings convert to0underNumber(). Trim and check for""before parsing optional numbers. - Calling
val.toString()on nullable values: Calling.toString()onnullorundefinedcrashes with aTypeError. UseString(val)instead.
Frequently Asked Questions
What is the difference between 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.
How does parseInt() differ from Number()?
Number.parseInt("42px", 10) stops at "p" and returns 42, whereas Number("42px") rejects the trailing letters and returns NaN.
How do I convert a timestamp number into a readable date string?
Pass the millisecond number to new Date(timestamp).toISOString().
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.