Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

When I add a + before a number in quotes like +"123", it is converting to typeof number but if I add like "123"+, it is waiting for next operands. Why? Why in the first case it is converting to a number?

like image 751
Mr_Perfect Avatar asked Jan 05 '17 10:01

Mr_Perfect


2 Answers

In the first case, you use an Unary plus +

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

in the second you are using just an Addition

The addition operator produces the sum of numeric operands or string concatenation.

like image 170
Nina Scholz Avatar answered Nov 17 '22 10:11

Nina Scholz


As you have + and - symbols(as unary operators) to numbers prepended only not appended. In the same way, when you add some + or - to strings, same applies and are if able to convert to numbers they will be converted to numbers. But when you append that, it is treated as binary operator. So, concatenates.

like image 1
Sai Avatar answered Nov 17 '22 10:11

Sai