๐ฐ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