Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why 1 + + "1" === 2; +"1" + + "1" === 2 and "1" + "1" === "11" in javascript [duplicate]

Tags:

javascript

Does the addition operator before char in javascript convert them to number?

1 + + "1" === 2; 
+"1" + + "1" === 2;
"1" + "1" ===  "11"

Earlier question doesn't explain why it's happening only tells us various ways of converting strings to number and vice versa.

like image 955
vipin goyal Avatar asked Aug 26 '17 07:08

vipin goyal


3 Answers

1 + + "1" === 2; 

Unary operator + has higher precedence, so +"1" will be evaluated first, converting "1" into integer of value of 1, so it will become

1+1 === 2

The second line

+"1" + + "1" === 2;

This is similar. Unary operator + has higher precedence, so both +"1" will be evaluate to positive integer value of 1.

"1" + "1" ===  "11"

Because in JavaScript + is also string concatenation operator if both operands are string, this will concat both strings.

More information https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

Update: @torazaburo is correct.

  • The evaluation of +"1" in code here has nothing to do with operator precedence.

  • String concatenation will happen if either operand is string.

like image 160
Zamrony P. Juhara Avatar answered Nov 14 '22 05:11

Zamrony P. Juhara


In JS there is implicit type coercion. For instance, the binary plus operator coerces a number into string if the other operand is a string. "1" + 2 === "12" or 3 + "4" === "34".

However when used with a single operand it works backwards and +"1" coerces the "1" string to a number 1. Just like parseInt("1").

So +"1" + 3 === 4

like image 27
Redu Avatar answered Nov 14 '22 05:11

Redu


What you are looking for is the unary plus. Lets analyze the first 2 cases:

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.

1 + + "1" === 2

+ "1" part is converting the string "1" to a number 1. The number 1 is then added to the other number 1 resulting in 2 === 2

+ "1" + + "1" === 2

Same as above, but instead there are 2 unary operation now. So both string "1" are converted to number 1 resulting in 2 === 2

like image 3
lap00zza Avatar answered Nov 14 '22 03:11

lap00zza