🔰type conversion
JS ⟩ value ⟩ type ⟩ conversion
When JS expects a boolean, a value of any type can be supplied, and JS will convert it as needed. The same is true for all types.
// ⭐ explicit type conversion
Number(' 012'), // 12
String(34), // '34'
Boolean({}), // true
// ⭐ implicit type conversion
+' 012', // === Number(' 012')
34 + '', // === String(34)
!!{}, // === Boolean({})
replit: type conversion table (require: TableMaker)
┌── (primitive?)
│ (-> number) (-> string)
│ x desc +x String(x)
────────────────────────────────────────────────────────────────────
✅ null 0 "null"
────────────────────────────────────────────────────────────────────
✅ undefined NaN "undefined"
────────────────────────────────────────────────────────────────────
✅ 0 0 "0"
✅ Infinity Infinity "Infinity"
✅ NaN NaN "NaN"
────────────────────────────────────────────────────────────────────
✅ "" empty str 0 ""
✅ "1.2" numeric 1.2 "1.2"
✅ "one" non-numeric NaN "one"
────────────────────────────────────────────────────────────────────
✅ true 1 "true"
✅ false 0 "false"
────────────────────────────────────────────────────────────────────
❌ {a:1} NaN "[object Object]"
❌ [] empty arr 0 ""
❌ [6] one numeric 6 "6"
❌ ['a'] any other NaN "a"
❌ new Date 1667314617317 "Tue Nov 01 2022 14:...
❌ /regex/ NaN "/regex/"
────────────────────────────────────────────────────────────────────
❌ () => {} NaN "() => {}"
❌ class {} NaN "class {}"
────────────────────────────────────────────────────────────────────
isNaN(x)
will try to convertx
to a number first❗Number.isNaN(x)
never do conversions.
any non-nullish value has .toString() method, usually equivalent to String().
operators
unary plus (+) - any -> number (except symbol, bigint)
double tilde (~~) - nearest integer towards zero.
not not (!!) - any -> bool.
type conversions
💍 falsy
ℹ️ type conversion is involved in sloppy equality (==)
ℹ️ type conversion is involved in comparison operator.
⚠️ values that try to convert to a number may result in NaN❗
⛔ possible errors:
replit: type conversion examples
let n = NaN;
8 + " cats", // "8 cats" (8 -> '8')
n + " dogs", // "NaN dogs" (NaN -> 'NaN')
'3' * '8', // 24 ('3' -> 3, '8' -> 8)
4 - "a", // NaN ('a' -> NaN)
String ⟩ String coercion
Object.prototype.toString() - object to string.
Object.prototype.valueOf() - object to (primitive) value, if exists.
Last updated