JavaScript: JavaScript Type Conversion
Type conversion is the most error-prone part of JavaScript. A number typed into a form? Turns out it's a string! "5" + 3 gives "53" instead of 8 — every beginner encounters these "surprises."
1. Type Conversion Methods and Pitfalls
(1) Why Type Conversion Matters
HTML form input values are always strings, even with type="number". You must convert types before doing arithmetic, or the results will be unpredictable.
<!-- Container element -->
<div id="demo"></div>
<!-- Script tag -->
<script>
const input = "42";
const result = input + 8;
document.getElementById("demo").textContent = 'input + 8 = ' + result + ' (type: ' + typeof result + ')';
</script>
(2) Explicit Conversion: String(), Number(), Boolean()
Calling conversion functions explicitly makes your intent clear — this is the recommended approach:
| Conversion | Syntax | Example |
|---|---|---|
| To string | String(value) |
String(123) → "123" |
| To number | Number(value) |
Number("42") → 42 |
| To boolean | Boolean(value) |
Boolean(0) → false |
(3) Implicit Conversion: + Concatenation and == Comparison
The JavaScript engine performs automatic type conversion that often produces unexpected results:
+operator: if either side is a string, the other gets converted to a string for concatenation==comparison: converts types before comparing, with complex rules that are hard to remember
<!-- Script tag -->
<script>
console.log("5" + 3); // "53" (number 3 converted to string)
console.log("5" - 3); // 2 (string "5" converted to number)
console.log("" == 0); // true (empty string converted to 0)
console.log(null == undefined); // true
</script>
(4) Common Pitfalls
These are high-frequency gotchas in interviews and real-world development:
<!-- Script tag -->
<script>
console.log("5" + 3); // "53" + concatenates when it sees a string
console.log("5" - 3); // 2 - only does subtraction, converts string to number
console.log("5" * 3); // 15 * also converts to number
console.log(true + 1); // 2 true converts to 1
console.log(false + 1); // 1 false converts to 0
console.log("" + 0); // "0" number converts to string
console.log("" == 0); // true both sides convert to numbers
console.log(null == 0); // false null only loosely equals undefined
console.log("0" == false); // true both convert to 0
</script>
Remember this rule: + concatenates when it encounters a string; all other arithmetic operators convert strings to numbers.
(5) Number() Conversion Rules
| Input | Result |
|---|---|
Number("42") |
42 |
Number("3.14") |
3.14 |
Number("") |
0 (empty string → 0, classic gotcha) |
Number(" ") |
0 (whitespace-only string → 0) |
Number("42px") |
NaN (contains non-numeric characters → NaN) |
Number(true) |
1 |
Number(false) |
0 |
Number(null) |
0 |
Number(undefined) |
NaN |
Empty string converts to 0 instead of NaN — this design has tripped up countless developers.
(6) Boolean() Conversion Rules (Falsy Values)
These 6 values convert to false and are called falsy values. Everything else is true:
<!-- Script tag -->
<script>
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
</script>
Note: Boolean("0") is true, and Boolean([]) is also true — non-empty strings and non-empty arrays are truthy.
(7) === Strict Equality vs == Loose Equality
| Operator | Behavior | Recommendation |
|---|---|---|
=== |
Returns false if types differ | Always use |
== |
Converts types before comparing | Avoid |
<!-- Script tag -->
<script>
console.log(5 === "5"); // false (different types)
console.log(5 == "5"); // true (string converted to number first)
console.log(null === undefined); // false
console.log(null == undefined); // true
</script>
Iron rule: always use ===, never ==. Unless you know exactly what you're doing (e.g., value == null can match both null and undefined).
▶ Example: Type Conversion Comparison
▶ Try it Yourself▶ Example: Boolean() Falsy Values Quick Reference
▶ Try it Yourself▶ Example: Form Input Calculation
▶ Try it Yourself▶ Example: === vs == Comparison
▶ Try it Yourself❓ FAQ
Number(x), String(x), or Boolean(x) to actively change the type. Type coercion happens implicitly, for example in "5" - 3 or if (x), where the engine converts automatically. Both follow the same underlying rules; the difference is whether the conversion function is written explicitly in the code."5" + 3 produce "53", while "5" - 3 produces 2?+ operator encounters a string, it prioritizes string concatenation, so "5" + 3 produces "53". In contrast, -, *, /, and % only perform mathematical operations and convert their operands to numbers, so "5" - 3 produces 2. This is a common pitfall caused by the ambiguity of +.String(obj) or JSON.stringify(obj) to convert an object to a string?String(obj) usually calls the object's toString(), producing "[object Object]"; JSON.stringify(obj) serializes it into a JSON string, such as '{"a":1}'. Use JSON.stringify when you need readable, transferable data, and use String when you just need a string representation.📖 Summary
- Convert strings to numbers with
Number(),parseInt(),parseFloat()— parseInt ignores trailing non-digits - Convert numbers to strings with
String(n),n.toString(), orn.toFixed(2)for decimal control - Implicit coercion happens automatically:
==coerces types (use===),+with strings becomes concatenation - Common traps:
"5" - 3is 2,"5" + 3is "53",null == undefinedis true - Convert to Boolean:
!!valueorBoolean(value)— six falsy values:false/0/""/null/undefined/NaN
📝 Exercises
- Without running the code, predict the results of these expressions:
"10" + 5,"10" - 5,"10" * "2",true + true,Boolean("false"),"1" == 1,"1" === 1. Then write code to verify. - Write a
calculateBMI(weight, height)function where parameters come from form inputs (strings). The function should convert types internally before calculating BMI, and handle empty or invalid inputs (return an error message). - Write a
strictCompare(a, b)function that uses only===for comparison. If the types differ, return"Different types, cannot compare"directly; if types match, return the comparison result.