JavaScript Type Conversion

Type conversion changes a value from one data type to another. It can be explicit (coercion using functions) or implicit (happens automatically). Understanding these conversions helps avoid unexpected results in code.

Key Topics

String Conversion

Use String(value) or value.toString() to convert values to strings.

Number Conversion

Use Number(value) to convert strings to numbers. parseInt() and parseFloat() handle strings with digits.

Boolean Conversion

Use Boolean(value) to convert to boolean. Truthy values become true, falsy values ("", 0, null, undefined, NaN) become false.

Implicit Conversion

JavaScript may convert types automatically in operations like "5" * 2, resulting in a number. Always be mindful of these conversions.

console.log("5" * 2); // 10 (string to number)
console.log("5" + 2); // "52" (number to string)

Output

> 10

> "52"

Explanation: Multiplication coerces "5" into a number. Addition with a string results in string concatenation.

JavaScript Usage in DOM

Convert user input (always a string) to numbers for calculations, or booleans to handle conditional display of elements.

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Type Conversion in DOM</title></head>
<body>
    <h1>Type Conversion Demo</h1>
    <input type="text" id="numInput" placeholder="Enter a number">
    <button onclick="convertType()">Convert</button>
    <p id="result"></p>

    <script>
        function convertType() {
            let val = document.getElementById("numInput").value;
            let num = Number(val);
            if (!isNaN(num)) {
                document.getElementById("result").textContent = "Converted to number: " + num;
            } else {
                document.getElementById("result").textContent = "Invalid number";
            }
        }
    </script>
</body>
</html>

Key Takeaways

  • Explicit Conversion: Use String(), Number(), Boolean(), etc.
  • Implicit Conversion: JavaScript may convert types automatically in expressions.
  • DOM Integration: Convert user input strings to numbers for calculations.