Module 09 // Core JavaScript

Type Conversion & Equality

Module Objective

Implicit vs explicit coercion, ToPrimitive/ToNumber, == vs ===, truthy/falsy rules

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 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 `===`.**
// Example 2
// 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.
// Example 3
// 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.

Engine & Memory Architecture

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."