Coersion (CR25)
1: const num = 42;
2: const str = String(num); // Number to string
3: const bool = true;
4: const nul = null;
5: const und = undefined;
6:
7: const numFromStr = Number(str); // String to number
8: const numFromBool = Number(bool); // Boolean to number (1 for true, 0 for false)
9: // const numFromBig = Number(big); // BigInt to Number - potential loss of precision if outside Number range. Explicit conversion is discouraged. Better use BigIntLib.
10: const numFromNul = Number(nul); // Null to number (0)
11: const numFromUnd = Number(und); // Undefined to number (NaN).
12: const numSpecial = parseInt("hello"); // NaN
13:
14: console.log(numFromStr);
15: console.log(numFromBool);
16: console.log(numFromNul);
17: console.log(numFromUnd);
18: console.log(numSpecial);
19:
Number Conversions: 42 1 0 NaN NaN
Coersion context:
ES6 context:
Comments (
)

Link to this page:
http://www.vb-net.com/JavascriptES6/CR25.htm
|