Type Conversion (Explicit)
How to intentionally convert values between strings, numbers, and booleans using JavaScript's built-in casting functions.
What is explicit type conversion?
While JavaScript often coerces types automatically (implicit coercion), it is much safer to convert them intentionally (explicit conversion).
JavaScript provides three primary functions for this: String(), Number(), and Boolean().
Why cast explicitly?
Implicit coercion can lead to very unpredictable bugs, like 5 + 3 evaluating to 53. By explicitly converting the string to a number first using Number('5') + 3, the code evaluates predictably to 8.
Explicit casting makes your intent obvious to other developers reading your code.
How casting behaves
String(value): Converts almost anything to a sensible string. String(null) becomes 'null', and String([1, 2]) becomes '1,2'.
Number(value): Very strict. If a string contains any letters, it evaluates to NaN (Not-a-Number). Number(true) becomes 1, and Number(false) becomes 0.
Boolean(value): Converts based on 'truthiness'. The six falsy values (0, '', null, undefined, NaN, false) become false. Everything else, including empty arrays [] and empty objects {}, becomes true.
Casting Simulator
See how different JavaScript values are handled when forced through the three main type conversion functions.
Explicit Casting
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use explicit conversion (
Number(),String(),Boolean()) to make your code predictable. Number()is strict and returnsNaNif the string contains non-numeric characters.Boolean()evaluates based on truthiness. Empty arrays and objects are truthy.parseInt()extracts numbers from strings, whereasNumber()validates the whole string.
Done with this concept?
Mark it complete to track your progress. No login needed.