JavaScript Roadmap — Day 6: Type Conversion and Coercion

 

JavaScript · Day 6 of 180 · Beginner Phase

Type Conversion and Coercion

JavaScript secretly changes your data types behind your back. This is called coercion — and it is responsible for some of the most confusing bugs beginners ever face.

Day 6 / 180
Beginner Phase

Look at this code carefully and predict what it will print before reading the answers:

JavaScript — Can you predict the output?
// What does each line print?
console.log("5" + 3);
console.log("5" - 3);
console.log(true + 1);
console.log(false + 1);
console.log("" + 5);
console.log("5" * "3");

Answers:

"53" — string + number = string concatenation
2 — string - number = number subtraction
2 — true converts to 1
1 — false converts to 0
"5" — empty string + number = string
15 — both strings convert to numbers for multiplication

If any of those surprised you — this lesson is exactly what you need. JavaScript is doing something called type coercion — silently converting your data from one type to another without telling you. Understanding this completely removes an entire category of bugs from your code forever.

1. Explicit vs Implicit — You vs JavaScript

There are two ways a type changes in JavaScript. Either you deliberately convert it — or JavaScript secretly converts it for you:

Type Who does it Example Safe?
Explicit Conversion You — intentionally Number("5") ✅ Predictable
Implicit Coercion JavaScript — secretly "5" - 3 ⚠️ Unpredictable

2. Explicit Conversion — You Are in Control

JavaScript gives you built-in functions to convert types manually. These are predictable, safe, and always do exactly what you expect. Every professional JavaScript developer uses these daily:

JavaScript — Converting to Number
Number("42")       // 42
Number("3.14")     // 3.14
Number("")         // 0  ← empty string becomes 0
Number("hello")    // NaN ← cannot convert text
Number(true)       // 1
Number(false)      // 0
Number(null)       // 0
Number(undefined)  // NaN

parseInt("42px")      // 42  ← stops at non-number
parseInt("3.9")       // 3   ← cuts decimal part
parseFloat("3.9em")   // 3.9 ← keeps decimal

+"42"     // 42  ← unary + shortcut
+true     // 1
+""       // 0
JavaScript — Converting to String
String(42)          // "42"
String(true)        // "true"
String(null)        // "null"
String(undefined)   // "undefined"

(255).toString(16)   // "ff"  (hexadecimal)
(8).toString(2)     // "1000" (binary)
JavaScript — Converting to Boolean
// The 6 FALSY values
Boolean(false)      // false
Boolean(0)          // false
Boolean("")         // false
Boolean(null)       // false
Boolean(undefined)  // false
Boolean(NaN)        // false

// EVERYTHING else is truthy
Boolean(1)          // true
Boolean([])         // true ← empty array is TRUTHY!
Boolean({})         // true ← empty object is TRUTHY!
Boolean("0")        // true ← "0" as STRING is TRUTHY!

!!0       // false — short way
!![]      // true

3. Implicit Coercion — JavaScript's Secret Decisions 🔥

When you use operators like +, -, *, /, JavaScript decides what type to convert things to. Its decisions are not always obvious:

The + Operator — The Sneaky One

JavaScript — The + Operator trap
"5" + 3         // "53"  NOT 8!
3 + "5"         // "35"
1 + 2 + "3"     // "33"  (1+2=3, then 3+"3"="33")
"1" + 2 + 3     // "123"
true + 1        // 2  (true = 1)
false + 1       // 1  (false = 0)
null + 1        // 1  (null = 0)
undefined + 1   // NaN

Other Operators — Number Always Wins

JavaScript — - * / always convert to Number
"10" - 3        // 7
"5" * "3"       // 15
"5" * null      // 0
"5" * undefined // NaN
"hello" * 2    // NaN
"10" / "2"      // 5
true / false    // Infinity (1 / 0)

4. The == Operator — The Most Dangerous Coercion 🔥

Loose equality == converts types before comparing. Study these carefully — they appear in every JavaScript interview:

JavaScript — == loose equality surprises
0 == false        // true
"" == false       // true
"5" == 5          // true
[] == false        // true  ([] → "" → 0)
[] == 0           // true
[1] == 1         // true

// The fix — always use ===
0 === false       // false ✅
"" === 0          // false ✅
"5" === 5         // false ✅

🔥 The rule that saves everything: Always use === instead of ==. The only exception is value == null which catches both null and undefined — a pattern senior developers use intentionally.

5. Pro Tips

Pro Tip #1 — Always validate before converting
When converting user input to a number always check if the result is NaN using isNaN() or Number.isNaN() afterward. User input like "abc" will produce NaN silently and every calculation involving it will also be NaN.
Pro Tip #2 — parseInt needs a radix argument
Always write parseInt("10", 10) not just parseInt("10"). Without the radix older browsers could interpret strings starting with "0" as octal (base 8). Small habit, real bug prevention.
Pro Tip #3 — Empty array [] is truthy but == false
Boolean([]) is true but [] == false is also true. Because == does not use Boolean conversion — it converts both sides to numbers first. Classic interview trap question.

6. Quick Reference — Conversion Rules

Value → Number → String → Boolean
00"0"❌ false
11"1"✅ true
""0""❌ false
"0"0"0"✅ true
"hello"NaN"hello"✅ true
true1"true"✅ true
false0"false"❌ false
null0"null"❌ false
undefinedNaN"undefined"❌ false
[]0""✅ true

7. Try It Yourself

Run the code and study every output. Then try changing the operators and values to test your understanding.

✏️ Try it Yourself — Type Coercion
OUTPUT
// Click Run Code to see output
💡 Code edit karo aur Run dabao!

8. Practice Tasks

Task 1 — Easy: Predict Before Running

Before running — write your predicted output next to each line. Then run and check: "10" + 5, "10" - 5, true + true + true, null + undefined, "5" * false.

Task 2 — Medium: Safe Input Converter

Write a function safeToNumber(value) that converts any input to a number. If the result is NaN return 0 as fallback. Test with: "42", "hello", true, null, undefined, "".

Task 3 — Hard: The Coercion Detective

These all return true with ==. Explain exactly why for each: [] == false, "" == 0, [1] == 1, null == undefined. Then rewrite with === and explain why they return false.

Next Lesson
Day 7 — Arithmetic Operators
Read Next Lesson →
Want daily web dev tips?
Follow Muhammad Waheed Asghar for daily JavaScript and CSS tips!

Popular Posts