-2

Why does alert("1" - - "1") return 2?

I'm not entirely sure what is going on here to create the result as 2?

I came across the problem here: http://davidshariff.com/js-quiz

Malcr001
  • 8,179
  • 9
  • 44
  • 57

1 Answers1

3

it's like writing 1 - (-1) which is 1 + 1 = 2

the problem in js is that if you use + between 2 string it means concating them thus resulting 11

EDIT: thanks to iamnotmaynard comment i was able to find this post

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

Community
  • 1
  • 1
ymz
  • 6,602
  • 1
  • 20
  • 39
  • This only answers part of the question. There is also confusion about type coercion. – Reinstate Monica -- notmaynard Nov 24 '14 at 21:29
  • When you use the "-" infix, javascript assumes that both of the arguments are numbers. For every other data type this operation does not make any sense. So if it is a string it tries to parse it as a number. You can try "test" - "something". This will return NaN. – Schnodderbalken Nov 24 '14 at 21:33