Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different result for "1"+"1" & "1" - - "1" in javascript [duplicate]

Tags:

javascript

JavaScript Coercion, Order Precedence and associativity can be confusing but I use below link to understand it,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

But I am still not getting why "1"+"1" resulting into "11" and "1"- - "1" resulting into 2,

- - should be converted to + and it should process like "1"+"1", What am I missing here?

You can test it here:

console.log("1" + "1");
console.log("1"- - "1");
like image 234
pk_code Avatar asked Dec 24 '22 11:12

pk_code


2 Answers

The second - of the two -s is interpreted as unary -. The unary operator has higher precedence so "1"- - "1" is the same as "1" - (-"1") which is then the same as "1" - (-1) and since - is only used on numbers, the aforementionned operation becomes 1 - (-1) which evaluates to 2.

like image 137
ibrahim mahrir Avatar answered Dec 26 '22 01:12

ibrahim mahrir


“1”+“1” will be interpreted as a string concatenation. When evaluating an expression, + will do a concatenation if one of the operand is of type string which is not the case for the operator -.

“1” - - “1” in javascript, the operator - tries to do a parsing of the operands it has. If it cannot parse them into number it will return NaN. So “1” - - “1” is similar to “1” - (- “1”) . What happens is that because there is the operator - there will be a parsing of "1" to number (first operand) and a parsing of the second operand (-"1") also to number.

Actually both operators are a little different:

  • "foo" + 1 will return foo1, because + will do a concatenation

  • whereas: "foo" - 1 will return NaN because the first operand cannot be parsed into a number. The same rule applies to the operator / and *.

like image 39
edkeveked Avatar answered Dec 26 '22 01:12

edkeveked