Because JavaScript is dynamically typed, values frequently transition from one data type to another during program execution. This transformation happens in two distinct ways: Explicit Type Conversion (directed intentionally by the developer) and Implicit Type Coercion (performed automatically by the JavaScript engine).
Figure 3: Summary of JavaScript 8 Falsy values and Strict (===) vs Loose (==) Equality matrix.
Writing clear, predictable code requires explicit conversion using built-in wrapper constructors:
// 1. Number() constructor (Strict)
Number("42"); // 42
Number("3.14"); // 3.14
Number(""); // 0
Number("Hello"); // NaN
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number(undefined); // NaN
// 2. parseInt() and parseFloat()
parseInt("100px", 10); // 100 (Parses leading digits with base-10 radix)
parseFloat("12.5rem"); // 12.5
// 3. Unary Plus Operator (+)
+"99"; // 99 (Fast concise shorthand for Number())
// 1. String() constructor
String(123); // "123"
String(true); // "true"
String(null); // "null"
String(undefined); // "undefined"
// 2. .toString() method (Fails on null & undefined!)
let num = 255;
num.toString(16); // "ff" (Converts to hexadecimal string!)
In JavaScript, every value is intrinsically either truthy or falsy when evaluated in a boolean context:
// The ONLY 8 Falsy Values:
Boolean(false); // false
Boolean(0); // false
Boolean(-0); // false
Boolean(0n); // false (BigInt zero)
Boolean(""); // false (Empty string)
Boolean(null); // false
Boolean(undefined); // false
Boolean(NaN); // false
// EVERYTHING ELSE IS TRUTHY! (Notice common beginner traps):
Boolean([]); // TRUE! (Empty array is truthy)
Boolean({}); // TRUE! (Empty object is truthy)
Boolean("0"); // TRUE! (Non-empty string is truthy)
Boolean("false"); // TRUE! (Non-empty string is truthy)
Implicit coercion occurs when operators encounter unexpected data types. JavaScript silently converts one or both operands to find common ground:
| Expression | Output | Under-the-Hood Coercion Mechanics |
|---|---|---|
"5" + 2 |
"52" |
Plus operator with a string triggers string concatenation. Number 2 is coerced to "2". |
"5" - 2 |
3 |
Minus operator only works mathematically. String "5" is coerced to Number 5. |
"10" * "2" |
20 |
Multiplication forces numeric coercion on both strings. |
true + 5 |
6 |
Boolean true coerces to 1. (1 + 5 = 6). |
false + null |
0 |
false coerces to 0; null coerces to 0. (0 + 0 = 0). |
[] + {} |
"[object Object]" |
Array converts to empty string ""; Object converts to "[object Object]". |
Frequent Exam Trap: "Explain the output of: console.log([] == ![]);"
!) has higher precedence than ==.[] is truthy, so ![] evaluates to boolean false.[] == false.false coerces to 0.[] converts to string "", which coerces to number 0.0 == 0 evaluates to true!==) is dangerous and strict equality (===) is mandatory in production.
How do you document your code and keep it clean for team collaboration? Proceed to: JavaScript Comments & JSDoc Standards →