JavaScript: JavaScript Type Conversion

🗓 Last updated: 2026-11-30👤 Written by: Casey✓ Reviewed by: Gray🏷 Category: JavaScript Tutorial

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:JSON.stringify parseFloat() toString() parseInt() Number() String

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

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

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

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

Related Global Methods:JSON.stringify parseFloat() toString() parseInt() Number() String

❓ FAQ

Q What is the difference between type conversion and type coercion in JavaScript?
A Type conversion usually refers to explicit conversion, such as using 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.
Q Why does "5" + 3 produce "53", while "5" - 3 produces 2?
A When the + 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 +.
Q In JavaScript, should I use String(obj) or JSON.stringify(obj) to convert an object to a string?
A The results differ: 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

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

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

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

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