JavaScript: JavaScript Type Conversion

Last updated: 2026-10-13

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."

Related Global Methods:parseFloat() parseInt() Number()

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.

HTML
<div id="demo"></div>
<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:

HTML
<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:

HTML
<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:

HTML
<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
HTML
<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

Related Global Methods:parseFloat() parseInt() Number()

❓ FAQ

Q Why does "5" - 3 equal 2 instead of throwing an error?
A Because the - operator only performs math, so JavaScript automatically converts the string to a number. Only the + operator is ambiguous (it can be addition or concatenation), so it concatenates when it sees a string. All other operators (-, *, /, %) always convert to numbers.
Q Why does Number("") return 0 instead of NaN?
A This is a legacy design choice. An empty string is considered to have "no number," equivalent to 0. This means Number(input.value) returns 0 for empty fields instead of NaN, which can mislead downstream logic. Use input.value.trim() === "" to check for empty values first.
Q Why is null == 0 false?
A In == comparisons, null only converts to/from undefined — it doesn't convert to numbers. So null == 0 is false, but null == undefined is true. This is a special case defined by the specification.

📖 Summary

📝 Exercises

  1. 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.
  2. 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).
  3. 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏