Skip to content
Concept 10 // Module 01: JavaScript Foundations & Environment

Type Conversion & Type Coercion

Module 01: JavaScript Foundations & Environment•Concept 10 of 100• 5 min read

Type Conversion & Type Coercion

**Coercion** is the automatic or implicit conversion of values from one data type to another. Understanding how JS converts types is critical for mastering equality checks (`==` vs `===`) and avoiding hidden bugs.

The Core Concept

Syntax Reference
// 1. Explicit Conversion
Number("42");   // 42
String(100);    // "100"
Boolean(1);     // true

// 2. Implicit Coercion (Avoid!)
"5" + 5;        // "55" (Number to String)
"5" - 5;        // 0 (String to Number)
if ("") { ... } // "" is Falsy

// 3. Truthy vs Falsy
// Falsy: false, 0, "", null, undefined, NaN
// Truthy: Everything else! (including {}, [], "0")

Live Interactive Studio

Loose equality `==` tries to force types to match. Strict equality `===` checks both value and type. **Always use `===`.**
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Comparison Trap

// 1. Comparison Trap
console.log(false == 0);  // true
console.log("" == 0);     // true
console.log([] == 0);     // true

console.log(false === 0); // false (Correct!)
console.log("" === 0);    // false
Loose equality `==` tries to force types to match. Strict equality `===` checks both value and type. **Always use `===`.**
02

Addition vs Subtraction

// 2. Addition vs Subtraction
console.log(10 + "5"); // "105" (String concatenation wins)
console.log(10 - "5"); // 5 (Numeric subtraction wins)

console.log(10 + true);  // 11 (true becomes 1)
console.log(10 + false); // 10 (false becomes 0)
The `+` operator overloaded for strings causes many bugs. If either operand is a string, JS converts the other to a string. Other math operators like `-` or `*` always convert to numbers.
03

Explicit Boolean conversion

// 3. Explicit Boolean conversion
const value = "Hello";

if (!!value) {
  console.log("Value exists!");
}

// Same as:
if (Boolean(value)) { ... }
Using `!!` (double not) is a common shorthand to convert any value to its boolean equivalent.
04

Explicit Type Casting

const num = Number('42');       // 42
const str = String(100);        // '100'
const bool = Boolean('hello');  // true
console.log({ num, str, bool });
Explicit conversion functions (Number, String, Boolean) clearly state developer intent.
05

Implicit String vs Number Coercion

console.log('5' + 3);  // '53' (String concatenation wins!)
console.log('5' - 3);  // 2 (Subtraction forces numeric coercion!)
console.log('5' * '2'); // 10
+ coerces to string if one operand is a string; -, *, / always coerce to numbers.
06

Symbol.toPrimitive Custom Coercion

const item = {
  price: 25,
  [Symbol.toPrimitive](hint) {
    return hint === 'number' ? this.price : `$${this.price}`;
  }
};
console.log(+item);      // 25
console.log(`${item}`);  // '$25'
Symbol.toPrimitive allows objects to control their exact coercion behavior.

Real-World Engineering Takeaways

Input Validation: Converting strings from `<input>` fields into Numbers for calculation.
Conditionals: Checking if a variable exists (is truthy) before using it.
Safe Equality: Using strict equality to ensure types haven't changed unexpectedly.
Formatting: Explicitly converting numbers or dates to strings for display.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
### **Coercion in Memory** **1. ToPrimitive:** - When an object is compared or added, JS calls an internal `ToPrimitive` abstract operation. - This creates a temporary primitive value in the **Stack** just for the calculation. **2. Type Table:** - The JS Engine maintains a mapping of how types convert (e.g., `null` becomes `0` in math, but `false` in boolean logic). - These conversions happen fast in the **CPU** registers during execution. **3. Safety:** - Avoid "magic" coercion. It makes code harder to read and harder for the JS Engine to optimize. - **Performance Tip:** Engines like V8 optimize code that maintains consistent types. Mixing types (`int` + `string`) can lead to "de-optimization."

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of Type Conversion & Type Coercion in JavaScript?

// Concept 10: Type Conversion & Type Coercion
// Understanding the core mental model
1 / 10