-3

I was trying to subtract the last digit out of a string after a loop, but then I found this mysterious phenomenon.

When I add two string of numbers, they concatenate:

"1" + "1" // = "11"

But when I subtract a string of number from another, it did not decatenate but was casted as a number instead:

"11" - "1" // = 10

Why does this happen? Should the result of the subtraction be "1" instead of 10? Wouldn't having some kind of consistency be better?


Edit: This question is NOT a duplicate of the question below, as this question is asking about the subtraction of two strings, instead of a string with a number.

Why does JavaScript handle the plus and minus operators between strings and numbers differently?

Hykilpikonna
  • 1,749
  • 2
  • 15
  • 32
  • 3
    That's the way the language works, like it or not. The `-` operator coerces its operands to numbers. – Pointy Sep 05 '19 at 11:18
  • 3
    And what would you expect `"101" - "1"` to do? `"100"` or `"001"`? And what about `"010" - "1"`? Or `"200" - "1"`? – Quentin Sep 05 '19 at 11:19
  • 1
    From what I understood, he expects string subtraction to work similar to a.replace(b, "") – volcanic Sep 05 '19 at 11:20
  • 3
    Re edit. It **is** a duplicate. The accepted answer even says "You cannot perform subtraction on strings" which **completely** applies in the slightly-different-in-an-non-significant-way that this question poses. – Quentin Sep 05 '19 at 11:22

1 Answers1

0

The subtraction operator (-) subtracts the number to the right of the operator from the number on the left.

When either of the operands are strings, an attempt is made to convert the strings to numbers.

Source

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
volcanic
  • 312
  • 1
  • 6