Numeric input conversion
Convert text from a form, prompt, query parameter, or other input source before arithmetic.
JS Puzzles · Const
Unary plus (+) is the one-operand form of the plus operator. It leaves numbers unchanged and converts non-number operands to numbers, like Number(...).
Unary plus is the prefix + applied to one value. It leaves numbers unchanged and converts other values to numbers, using the same conversion behavior as Number(...); this makes it useful when numeric input arrives as text.
+operand| Name | Type | Description |
|---|---|---|
operand | any JavaScript value | The single value to convert to a number. |
The operand converted to a number; an existing number is unchanged.
+ token represents either addition or unary conversion depending on whether it has one or two operands.true converts to the number 1.Number(...).+, unary conversion happens before addition because unary plus has higher precedence.const first = "10";
const second = "2";
const total = +first + +second;
console.log(total); // 12
console.log(+true); // 1
console.log(+""); // 0The unary plus converts each string operand to a number before the binary plus adds them.
Convert text from a form, prompt, query parameter, or other input source before arithmetic.
Force values such as booleans or empty strings through JavaScript’s numeric conversion rules.
Convert operands before a binary + expression so numeric strings are added rather than concatenated.
Unary plus is the prefix + operator with one operand. It returns numeric operands unchanged and converts non-numeric operands to numbers, like Number(...).
Follow-up: What happens with +true and +""? They become 1 and 0, respectively, because both values undergo numeric conversion.
Use +value when a value should be coerced to a number, such as text returned from input. For example, +"12" produces the number 12, whereas leaving the text unchanged can make binary + concatenate strings.
Follow-up: Why does +a + +b work for numeric strings? Each unary plus converts its operand before the binary addition runs.
JavaScript distinguishes unary plus from binary plus by the number of operands. Unary plus has one operand and converts it; binary plus has two operands and performs addition or string concatenation according to the operands.
Follow-up: Which runs first in +a + +b? Both unary operators run before the binary addition because unary plus has higher precedence.
Number()binary plus (+)unary minus (-)operator precedence