Converting on purpose — Number(), String(), Boolean() and unary +¶
Level: 101 · for anyone turning input text into numbers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: Unary +x is Number(x) with one exception — +1n throws where Number(1n) is 1; both read "" and " " as 0 and "12px" as NaN, and String(sym) works where "" + sym throws.
Keywords: Number(), String(), Boolean(), unary +
What the finished page will answer¶
- What do
Number(""),Number(" "),Number("12px"),Number("0x1f")andNumber("1_000")return? - Why does
+1nthrow aTypeErrorwhileNumber(1n)returns1? - What do
Number(null),Number(undefined),Number([]),Number([5])andNumber({})return, and which rule produces each? - Why does
String(Symbol("id"))work while"" + Symbol("id")and a template literal throw? - Is
!!valuethe same asBoolean(value)for every value?
Examples it will need¶
-
explicit_conversion_number_js.js— Number() and unary + on fifteen inputs side by side, with the one row where they differ -
explicit_conversion_string_and_boolean_js.js— String(), a template literal and Boolean() on symbols, BigInts, arrays and wrapper objects
See also¶
- Parsing numbers —
parseIntandparseFloat, which read a prefix instead - The
+operator — the implicit conversions these replace - Truthy and falsy — what
Boolean()returns for each value - BigInt — why a BigInt refuses unary plus
- Ruby text:
to_inever fails;Integer()does ↗ — the lenientto_iand the strictInteger()in Ruby - C: Parsing a number from text ↗ — three C parsers that fail in three different ways