Type Conversion & Coercion
JavaScript silently converts values between types — and sometimes that's a
superpower, sometimes a trap. Master the rules of explicit conversion and implicit coercion and
you'll finally understand why 0 == "0"
is true.
Type Conversion vs Coercion
JavaScript is a dynamically typed language — variables don't have fixed types. This means values often need to be converted from one type to another. There are two ways this happens:
Number(), String(), or
Boolean(). Also called type casting.
+ with a string
and a number.valueOf() and toString()
methods that JS calls automatically during coercion.Explicit Type Conversion
Use these built-in functions to convert types on purpose — always prefer explicit over implicit for clarity.
NaN if
conversion fails.true or false based on the
value's truthiness.+ is a shorthand for Number(),
e.g. +"42" → 42.// ── Number() conversion ──────────────────────
Number("42") // → 42
Number("3.14") // → 3.14
Number("") // → 0 (empty string!)
Number("hello") // → NaN
Number(true) // → 1
Number(false) // → 0
Number(null) // → 0 (surprise!)
Number(undefined) // → NaN
Number([]) // → 0 (empty array!)
Number([3]) // → 3
// ── String() conversion ──────────────────────
String(42) // → "42"
String(true) // → "true"
String(null) // → "null"
String(undefined) // → "undefined"
String([1, 2, 3]) // → "1,2,3"
(255).toString(16) // → "ff" (hex)
(8).toString(2) // → "1000" (binary)
// ── Boolean() conversion ─────────────────────
Boolean(0) // → false
Boolean("") // → false
Boolean(null) // → false
Boolean(undefined) // → false
Boolean(NaN) // → false
Boolean("hello") // → true
Boolean(42) // → true
Boolean([]) // → true (empty array is truthy!)
Boolean({}) // → true (empty object is truthy!)
// ── parseInt / parseFloat ────────────────────
parseInt("42px") // → 42 (stops at non-digit)
parseInt("3.9") // → 3 (truncates, not rounds)
parseInt("0xff", 16) // → 255 (hex parse)
parseFloat("3.14em") // → 3.14
parseFloat("abc") // → NaN
Implicit Coercion
Implicit coercion happens when JavaScript automatically converts a value to
fit an operation. The most common trigger is the + operator
— it both adds numbers and concatenates strings, making it the biggest coercion trap.
// ── The + operator (string wins!) ────────────
"5" + 3 // → "53" (number → string, then concat)
5 + "3" // → "53" (same)
"5" + true // → "5true"
"" + null // → "null"
// ── Other operators (number wins) ────────────
"5" - 2 // → 3 (string → number, then subtract)
"5" * "2" // → 10
"10" / "2" // → 5
true + true // → 2 (true → 1)
true + false // → 1
false - 1 // → -1 (false → 0)
// ── Comparison coercion ───────────────────────
"5" > 3 // → true (string coerced to number)
null > 0 // → false
null == 0 // → false (special case!)
null >= 0 // → true (🤯 bizarre!)
// ── Template literals always coerce to string ─
let n = 42;
console.log(`Value: ${n}`); // → "Value: 42"
+: if either operand is a string, the
other gets converted to string and they concatenate. With - * / %, both operands always convert to numbers.
Falsy & Truthy Values
Whenever JavaScript needs a boolean (like in an if condition), it coerces the value using the
ToBoolean rule. There are exactly 8 falsy values — everything
else is truthy.
falseThe boolean false0The number zero-0Negative zero0nBigInt zero""Empty stringnullNull valueundefinedUndefinedNaNNot a NumberThese are all truthy — some are surprising:
"0"Non-empty string"false"Non-empty string[]Empty array{}Empty objectfunction(){}Any functionInfinityInfinity-InfinityNegative infinity42Any non-zero number// Common pattern: guard against empty/null values
const username = "";
if (username) {
console.log("Welcome, " + username);
} else {
console.log("Please enter a name"); // runs: "" is falsy
}
// Double NOT !! converts any value to boolean
!!"" // → false
!!"hello" // → true
!!0 // → false
!![] // → true (empty array is truthy!)
!!null // → false
// Beware: "0" string is truthy, but Number("0") is falsy
if ("0") console.log("truthy"); // runs!
if (0) console.log("falsy"); // does NOT run
The Conversion Truth Table
Bookmark this table. These are the exact values JavaScript produces when converting common types:
| Original Value | → Number | → String | → Boolean |
|---|---|---|---|
| false | 0 | "false" | false |
| true | 1 | "true" | true |
| 0 | 0 | "0" | false |
| 1 | 1 | "1" | true |
| "" | 0 | "" | false |
| "0" | 0 | "0" | true ⚠️ |
| "hello" | NaN | "hello" | true |
| null | 0 | "null" | false |
| undefined | NaN | "undefined" | false |
| [] | 0 | "" | true ⚠️ |
| [3] | 3 | "3" | true |
| [1,2] | NaN | "1,2" | true |
| {} | NaN | "[object Object]" | true |
| NaN | NaN | "NaN" | false |
== (Loose) vs === (Strict) Equality
The double-equals == operator performs
type coercion before comparing. The triple-equals === compares both value and type — no coercion.
0 == "" // true 🤯
0 == "0" // true 🤯
"" == "0" // false 🤯
null == undefined // true 🤯
false == "0" // true 🤯
false == null // false
false == undefined // false
[] == false // true 🤯
[] == ![] // true 🤯🤯
0 === "" // false ✓
0 === "0" // false ✓
"" === "0" // false ✓
null === undefined // false ✓
false === "0" // false ✓
1 === 1 // true ✓
"a" === "a" // true ✓
null === null // true ✓
NaN === NaN // false (NaN quirk!)
=== unless you have a specific
reason to use ==. The only common legitimate use of == is checking for both null and undefined in one
check: if (value == null).
Object-to-Primitive Coercion
When an object appears in a context that expects a primitive (like addition
or a template literal), JavaScript calls its valueOf() and
toString() methods to convert it.
// Arrays join their elements with commas via toString()
[1, 2, 3] + [] // → "1,2,3"
[1, 2] + [3, 4] // → "1,23,4" (not [1,2,3,4]!)
// Objects call toString() → "[object Object]"
{} + [] // → 0 or "[object Object]" (context-dependent!)
[] + {} // → "[object Object]"
// Custom valueOf to control coercion
const money = {
amount: 100,
currency: "USD",
valueOf() { return this.amount; },
toString() { return `${this.amount} ${this.currency}`; }
};
money + 50 // → 150 (uses valueOf)
`Total: ${money}` // → "Total: 100 USD" (uses toString)
String(money) // → "100 USD"
Common Coercion Gotchas
These are the coercion surprises that trip up developers of all experience levels:
// 1. typeof NaN is "number"
typeof NaN // → "number" 🤯
NaN === NaN // → false (NaN ≠ NaN)
Number.isNaN(NaN) // → true ✓ (use this to check)
// 2. null arithmetic
null + 1 // → 1 (null → 0)
null + "1" // → "null1" (string concat)
// 3. The infamous [] + {} vs {} + []
[] + {} // → "[object Object]" (both to string)
{} + [] // → 0 (parser sees {} as empty block!)
// 4. Sorting numbers — default sort converts to strings!
[10, 9, 2, 100].sort() // → [10, 100, 2, 9] (lexicographic!)
[10, 9, 2, 100].sort((a, b) => a - b) // → [2, 9, 10, 100] ✓
// 5. parseInt stops at first non-numeric char
parseInt("12abc") // → 12 (not NaN!)
parseInt("abc12") // → NaN (can't start with letters)
// 6. Always pass radix to parseInt
parseInt("010") // → 10 or 8 (browser-dependent!)
parseInt("010", 10) // → 10 ✓ always decimal
// 7. Number.isFinite vs global isFinite
isFinite("42") // → true (coerces first!)
Number.isFinite("42") // → false (no coercion) ✓
Try It Yourself
Edit the code below and click ▶ Run Code to see type conversion in action. Click Run in Editor for a full-screen editor.
== instead of ===
is the #1 coercion bug. Also watch out for + with mixed
types — always check whether you want concatenation or addition.
What does "5" + 3
evaluate to in JavaScript?
- Explicit conversion uses
Number(),String(),Boolean(),parseInt(), andparseFloat()to deliberately change types. - Implicit coercion happens automatically —
+with a string concatenates;- * /always convert to number. - There are exactly 8 falsy values:
false, 0, -0, 0n, "", null, undefined, NaN— everything else is truthy. - Always use
===(strict equality) — it doesn't coerce types and produces predictable results. NaN !== NaN— useNumber.isNaN()to safely check for Not-a-Number.- Always pass the radix (e.g.
10) as the second argument toparseInt()to avoid ambiguity.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.