Tutorials JavaScript Type Conversion & Coercion
Ch 9 / 78
Chapter 8 Beginner 7 min read JavaScript

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.

What you'll learn
Explicit conversion with Number(), String(), Boolean()
Implicit coercion — how JS converts behind the scenes
Falsy and truthy values — all 8 falsy values
The == vs === difference and when each applies
parseInt, parseFloat, and toString tricks
Common coercion gotchas that trip up developers

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:

Explicit Conversion
You deliberately convert a value using built-in functions like Number(), String(), or Boolean(). Also called type casting.
Implicit Coercion
JavaScript automatically converts a value when the operation requires a specific type — for example, using + with a string and a number.
Abstract Operations
Under the hood, JS uses internal algorithms like ToNumber, ToString, and ToBoolean that define exactly how every value converts.
valueOf / toString
Objects have 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.

→ Number
Number()
Converts any value to a number. Returns NaN if conversion fails.
→ String
String()
Converts any value to its string representation. Never throws.
→ Boolean
Boolean()
Returns true or false based on the value's truthiness.
→ Integer
parseInt()
Parses a string and returns an integer. Accepts a radix (base) as second argument.
→ Float
parseFloat()
Parses a string and returns a floating-point number.
Shorthand
+ operator
The unary + is a shorthand for Number(), e.g. +"42" → 42.
JS — Explicit Conversion
// ── 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.

JS — Implicit Coercion Examples
// ── 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"
Watch Out
The rule with +: 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 false
0The number zero
-0Negative zero
0nBigInt zero
""Empty string
nullNull value
undefinedUndefined
NaNNot a Number

These are all truthy — some are surprising:

"0"Non-empty string
"false"Non-empty string
[]Empty array
{}Empty object
function(){}Any function
InfinityInfinity
-InfinityNegative infinity
42Any non-zero number
JS — Truthy / Falsy in Practice
// 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.

== Loose Equality (coerces types)
Converts types before comparing. Can produce surprising results.
==
0   == ""        // true  🤯
0   == "0"       // true  🤯
""  == "0"       // false 🤯
null == undefined // true  🤯
false == "0"     // true  🤯
false == null    // false
false == undefined // false
[] == false      // true  🤯
[] == ![]        // true  🤯🤯
=== Strict Equality (no coercion)
Compares both value and type. Predictable and recommended.
===
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!)
Best Practice
Always use === 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.

JS — Object Coercion
// 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:

JS — Gotchas to Memorise
// 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) ✓
Advertisement

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.

Live Editor
✎ Editor
👁 Preview
Common Mistake
Using == instead of === is the #1 coercion bug. Also watch out for + with mixed types — always check whether you want concatenation or addition.
Quick Check — Chapter 8

What does "5" + 3 evaluate to in JavaScript?

Chapter Summary
  • Explicit conversion uses Number(), String(), Boolean(), parseInt(), and parseFloat() 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 — use Number.isNaN() to safely check for Not-a-Number.
  • Always pass the radix (e.g. 10) as the second argument to parseInt() to avoid ambiguity.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel