</>
Skip to content
JavaScript lessons (37/64)

JavaScript — Type Conversion

Two kinds of conversion

Explicit — you call a conversion. Implicit (coercion) — JavaScript does it behind your back. Learn explicit cold; learn to recognize implicit.

To string

String(123);        // "123"
String(true);       // "true"
(123).toString();   // "123"
`${123}`;           // "123" — template literal coerces for you

123 + "";           // "123" — implicit, common in old code

To number

Number("42");       // 42    strict: whole string or NaN
Number("12px");     // NaN
Number("");         // 0     quirk!
Number(null);       // 0     quirk!
Number(undefined);  // NaN

parseInt("42px");   // 42    leading digits only
parseFloat("3.5em") // 3.5
+"42";              // 42    unary plus — strict like Number()

The + operator's dual personality:

"5" + 1      // "51"  any string → concatenation
"5" - 1      // 4     no string meaning → numeric coercion

Rule: convert user input explicitly (Number(input)) before math; never rely on - side effects.

To boolean

Boolean("hi");   // true
Boolean(0);      // false

!!value          // double-NOT idiom — same result

Falsy set (everything else is truthy):

false · 0 · "" · null · undefined · NaN

Coercion shows up in conditions automatically:

if (cart.length) checkout();      // 0 = falsy = skip
if (!error) proceed();

== coercion horror show

Loose equality converts operands before comparing:

"" == 0            // true
null == undefined  // true
"0" == 0           // true
[] == false        // true 😵

You will never need this chaos: always === / !==.

Modern precision: ??

|| falls back on ALL falsy values; ?? only on null/undefined:

const volume = 0;
volume || 50     // 50  😧 — 0 got treated as missing!
volume ?? 50     // 0   ✓ — 0 is real data
"" || "anon";    // "anon"
"" ?? "anon";    // ""  ✓

Defaults for numbers/strings that may legitimately be zero/empty → use ??.

Converting objects (a peek)

Objects coerce via toString/valueOf — [1,2].toString() is "1,2":

"array: " + [1, 2];   // "array: 1,2"
[] + []               // ""    both → ""
[] + {}               // "[object Object]"

Recognize these in quizzes; write them never.

Safe conversion helper pattern

function toInt(value, fallback = 0) {
    const n = parseInt(value, 10);
    return Number.isNaN(n) ? fallback : n;
}
toInt("42px", -1);   // 42
toInt("abc", -1);    // -1 — controlled failure instead of silent NaN

Mini Practice

  1. Log typeof after each conversion path from "3.14"
  2. Build the truth table of Number(""), Number(null), parseInt("")
  3. Fix "5" + 1 three ways (explicit Number, unary +, template literal)
  4. Replace three || fallbacks with ??; find the one whose behavior changed
  5. Write safeDivide(a,b) returning null on division by zero; test with ??

Next: bitwise → (next new topic: regexp)

Related Topics

Frequently Asked Questions about Type Conversion

What is Type Conversion in JavaScript?

Type Conversion is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Type Conversion?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Type Conversion.

Why is Type Conversion important in JavaScript?

Type Conversion is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.