Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7739

Why does this expression return 2 in javaScript?

I would think you might get 0, maybe because the strings are turned to 1's and the - operator causes a subtraction operation to take place?

"1" - - "1";

Thanks in advance!

Upvotes: 4

Views: 111

Answers (3)

Alex
Alex

Reputation: 8663

The - casts the string to a number and also acts as a minus sign.

1 - (-1) = 1 + 1 = 2

Upvotes: 2

dimitar veselinov
dimitar veselinov

Reputation: 138

1 - (-1) = 2. I dont see the issue? JavaScript will parse those as integers because of the minus sign, expecting math. It also happens if you multiply a numerical string by 1, aka the poor man's parseInt().

Upvotes: 1

axelduch
axelduch

Reputation: 10849

It's how math works

1 - (-1) = 1 + 1

Upvotes: 11

Related Questions