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