How does a string (like "123") convert to a number if I add + before it, but not after it?

When I add + in front of the number in quotation marks, for example +"123" , it is converted to typeof number , but if I add as "123"+ , it waits for the next operands. What for? Why in the first case is it converted to a number?

+6
source share
4 answers

In the first case, you use Unary plus +

The unary plus operator precedes its operand and evaluates its operand, but tries to convert it to a number if it has not already been. Although unary negation (-) can also convert non-numbers, unary plus is the fastest and preferred way to convert anything to a number, since it does not perform any other operations on the number. It can convert string representations of integers and floating point numbers, as well as non-string values โ€‹โ€‹of true , false and null . Integers in decimal and hexadecimal formats are supported ("0x" -represented). Negative numbers are supported (although not for hex). If he cannot parse a specific value, he will evaluate NaN .

in the second you use only addition

The addition operator produces a sum of numerical operands or string concatenation.

+8
source

Because you have the + and - characters (like unary operators) to numbers added just by non-enclosed ones. Similarly, when you add + or - strings to strings, the same applies and if they are able to convert to numbers, they will be converted to numbers. But when you add this, it is considered as a binary operator. So united.

+1
source

+"123" can be parsed as a unary + operator followed by line 123 . As you can see in the specification, the task of the unary + operator, in particular, is to distinguish its operand from the Number type.

"123"+ cannot be parsed as a valid JS expression, because the operand should always follow the token + , regardless of whether it should be parsed as a unary + operator or binary + add operator.

+1
source

You can understand this by reading this article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators

Unary operator. Trying to convert operand to number if it is not alread

0
source

Source: https://habr.com/ru/post/1013781/


All Articles