1

I want to find out why "+" and "-" operators behave differently in similar usage. And the usage convention for these operators.

An abstract example:

There are two different arrays, for simplicity, each have one number element.

To add or subtract the two elements from the different arrays, simply "+" and "-" by indexing them:

const arr1 = [1];
const arr2 = [2];

console.log(arr1[0] + arr2[0]); // 3
console.log(arr1[0] - arr2[0]); // -1

... all good

Now, for whatever reasons, try subtract them without indexing (given both only have one element each):

console.log(arr1 - arr2); // -1

... ok

Then, try to "add" them:

console.log(arr1 + arr2); // 12

wait ... concatenated?

Guess there's some kind of type conversion happening because when I use unary plus to ensure they are integers, it worked similar to subtraction:

console.log(+arr1 + +arr2); // 3

Aside: This question came about when I was working with Regex, an abstract example:

console.log("findthe1number".match(/\d/) + "findthenumber2".match(/\d/)); 
//12 concatenated

console.log("findthe1number".match(/\d/) - "findthenumber2".match(/\d/)); 
//-1 arithmetic

What I am keen to find out:

  • Confirm that when "+" is used with certain types, it'll automatically convert and apply concatenation.
  • If need to use '+' in cases similar to above, is forcing operands to integers the way to go
Enrichdev
  • 83
  • 2
  • 8
  • 2
    Does this answer your question? [Why does JavaScript handle the plus and minus operators between strings and numbers differently?](https://stackoverflow.com/questions/24383788/why-does-javascript-handle-the-plus-and-minus-operators-between-strings-and-numb); particularly references to the [specification](https://tc39.es/ecma262/#sec-applystringornumericbinaryoperator). – Sebastian Simon Apr 05 '21 at 06:59
  • It's all in the [specification](https://tc39.es/ecma262/)... – Robby Cornelissen Apr 05 '21 at 07:00
  • [wat](https://www.destroyallsoftware.com/talks/wat)? – Theraot Apr 05 '21 at 07:00
  • @SebastianSimon cheers for the link. It really helps to confirm and explain in details. Appreciate it! Will refine my research keywords in the future. – Enrichdev Apr 05 '21 at 07:07
  • @RobbyCornelissen. Thanks for the link to the docs. Helps with diving in under the hood. Will give the docs a good try, some light reading. – Enrichdev Apr 05 '21 at 07:14
  • @Theraot, LOL thanks for the link. A good laugh, Watman! Now, I can keep in mind the weird parts of the language. – Enrichdev Apr 05 '21 at 07:25

0 Answers0