Type Conversion
Type Conversion
Section titled “Type Conversion”Introduction
Section titled “Introduction”Type conversion is the explicit transformation of a value from one type to another using built-in functions like String(), Number(), and Boolean().
Why Do We Need This?
Section titled “Why Do We Need This?”User input comes as strings, API responses need parsing, and calculations require numbers. Type conversion bridges these gaps.
Real World Story
Section titled “Real World Story”Think of type conversion like a universal adapter for electronics. You have a US plug (string) that needs to fit into a European socket (number). The adapter (conversion function) transforms it.
Visual Explanation
Section titled “Visual Explanation”flowchart TD Input["User Input: '25' (string)"] Number["Number('25')"] Result["25 (number)"] Calculation["25 + 5 = 30"]
Input --> Number --> Result --> CalculationString Conversion
Section titled “String Conversion”String(123); // "123"String(true); // "true"String(null); // "null"String(undefined); // "undefined"String([1,2,3]); // "1,2,3"Number Conversion
Section titled “Number Conversion”Number("123"); // 123Number("12.5"); // 12.5Number("abc"); // NaNNumber(true); // 1Number(false); // 0Number(null); // 0Number(undefined); // NaNBoolean Conversion
Section titled “Boolean Conversion”Boolean(1); // trueBoolean(0); // falseBoolean("hello"); // trueBoolean(""); // falseBoolean(null); // falseBoolean(undefined);// falseBest Practices
Section titled “Best Practices”- Always use explicit conversion — avoid relying on coercion
- Validate conversions, especially with user input
- Use
parseInt()andparseFloat()for string parsing
Common Mistakes
Section titled “Common Mistakes”Number("123abc"); // NaN — not 123!parseInt("123abc"); // 123 — more forgivingSummary
Section titled “Summary”- Use
String(),Number(),Boolean()for explicit conversion - Always prefer explicit over implicit (coercion)
- Validate numeric conversions for user input