4

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");
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
pk_code
  • 2,608
  • 1
  • 29
  • 33
  • 6
    "*'- -' should be converted to +*" - why? – Oliver Charlesworth Dec 15 '17 at 16:12
  • 9
    With quotes around the operands the + is interpreted as string concatenation. The - - operators are casting the operands to numeric and subtracting -1 from 1 resulting in 2. – n8wrl Dec 15 '17 at 16:12
  • Just add parentheses according to the precedence/associativity rules, and you should have your answer. –  Dec 15 '17 at 16:16
  • I suggest you take a look at this topic also: https://stackoverflow.com/questions/36619870/why-is-1-1-n-true-in-javascript/36620136 – Baumi Dec 15 '17 at 16:21
  • 1
    *"What am I missing here?"* Different operators perform different kinds of type conversion. – Felix Kling Dec 15 '17 at 16:23
  • 2
    *"`- -` should be converted to `+`"* is absolutely not how operators work, in any language. "Conversion" does not happen on operators. `- -` is no more converted to `+` than `a * 1/b` is converted to `a / b`. – user229044 Dec 15 '17 at 16:38
  • Conversion and precedence comes later. First, the parser tries to successfully parse as much as possible. Your expression is parsed as string literal, minus operator, unary minus, string literal. Rest is common sense. – Salman A Dec 15 '17 at 18:08

2 Answers2

7

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.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
3

“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 *.

edkeveked
  • 17,989
  • 10
  • 55
  • 93