intermediate

Type Coercion in JavaScript

Understand how JavaScript converts types and avoid common pitfalls.

JavaScript is a loosely typed language that automatically converts values between types. This type coercion can be helpful but also causes subtle bugs if you do not understand it. Learning when and how JavaScript converts types, and how to control it explicitly, is essential for writing reliable code.

📚 Concepts & Theory

Implicit Coercion (Automatic)

"5" + 3    // "53" (number to string)
"5" - 3    // 2 (string to number)
"5" * "2"  // 10 (both to numbers)

String + Anything = String

"Hello" + 42      // "Hello42"
"Value: " + true  // "Value: true"

Comparison Coercion

5 == "5"   // true (coerces types)
5 === "5"  // false (strict, no coercion)

Truthy and Falsy

Falsy values: false, 0, "", null, undefined, NaN

if ("") console.log("yes");  // Does not run
if ("hello") console.log("yes");  // Runs

Explicit Conversion

String(123)     // "123"
Number("456")   // 456
Boolean(1)      // true
parseInt("10px")  // 10
parseFloat("3.14abc")  // 3.14

Best Practice: Use Strict Equality

// Always prefer === over ==
if (value === "5") { }

🎯 Your Challenge

Given `a = "10"` and `b = "5"`, first concatenate them (result1), then convert both to numbers and add them (result2). Use Number() for explicit conversion.

📝 Starter Code

JavaScript
// String values
const a = "10";
const b = "5";

// String concatenation
const result1 = 

// Numeric addition (convert first!)
const result2 = 
  • String + String concatenates
  • Use Number() to convert strings to numbers
  • parseInt and parseFloat also convert strings
  • Always use === for comparisons

Solution

JavaScript
const a = "10";
const b = "5";

const result1 = a + b;

const result2 = Number(a) + Number(b);

Explanation

When we use + with strings, JavaScript concatenates them, giving "105". To add numerically, we explicitly convert both strings to numbers using Number(), then add them to get 15.

⚠️ Common Mistakes to Avoid

  • Expecting + to add number strings
  • Using == instead of ===
  • Not understanding falsy values
  • Forgetting that Number() returns NaN for invalid strings

❓ Frequently Asked Questions

JavaScript was designed for flexibility in web browsers. Type coercion reduces errors for casual programmers but can cause issues in complex applications.
Use Number.isNaN(value) or the newer isNaN() function. Note: NaN === NaN returns false!

🔗 Related Concepts