2

Why is the last operation returning 20?

console.log(2 + 2); // equals 4
console.log("2" + "2"); // equals "22"
console.log(2 + 2 - 2); // equals 2
console.log("2" + "2" - "2"); // equals 20
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Siya Mzam
  • 4,655
  • 1
  • 26
  • 44
  • Infact doing ```"2"+"2"-"2"+"2"``` returns "202" this is intresting – Nishant S Vispute May 17 '21 at 05:45
  • Because 22 - 2. Note that strings do not have a `-` operator so the `"22"` is coerced into a number `22` – slebetman May 17 '21 at 05:45
  • 2
    Please don't upload [images of code](https://meta.stackoverflow.com/a/285557/3082296). They can't be copied to reproduce the issue, they aren't searchable for future readers and they are harder to read than text. Please post the actual code **as text** to create a [mcve]. – adiga May 17 '21 at 05:45
  • @NishantShamVispute `"2"+"2"-"2"+"2"` -> `"22" - "2" + "2"` -> `20 + "2"` -> `"202"` – adiga May 17 '21 at 05:47
  • @VLAZ there must be a couple of questions with chaining them together somewhere. – adiga May 17 '21 at 05:50
  • @adiga probably. Can't think of one off the top of my head but it might be under the type coercion rather than just `+` and `-`. I'll try to have a look when I have the time. – VLAZ May 17 '21 at 05:52
  • @adiga yeah i now get the concepts of **concatenation** & **coerce** – Nishant S Vispute May 17 '21 at 05:59

2 Answers2

11

+ and - evaluate left-to-right. When either operand is a string, the result is concatenation. When both are numbers, the result is addition.

In contrast, - will always coerce both sides to numbers.

'2' + '2' - '2'

does

// left-to-right
('2' + '2') - '2'
// both sides are strings, so concatenate
'22' - '2'
// operator is -, so coerce both sides to numbers
22 - 2
20
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

The signs + and - work very differently in string concatenation. The + operator gives direct concatenation instructions on strings whereas the - operator tries to coerce the types and perform the mathematical function.

console.log("2" + "2");
console.log(typeof ("2" + "2"));

console.log("2" - "2");
console.log(typeof("2" - "2"));
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • "*The + operator gives direct concatenation instructions on strings whereas the - operator tries to coerce the types and perform the mathematical function.*" The `+` operator will also do coercion when mixed type operands are used. Which is what happens with `s1 - s2 + s3` if all three are strings containing valid numerics. `s1 - s2` would produce a number, and `+ s3` would coerce back to string. – VLAZ May 17 '21 at 07:44
  • `+` operator will try to perform the concatenation by coercing if non-string values are given. – Charlie May 17 '21 at 08:31
  • Yes, as I said: "*when mixed type operands are used.*" – VLAZ May 17 '21 at 08:39
  • Yes. That is one way to put it. – Charlie May 17 '21 at 08:45