1

I was taking this JavaScript Quiz and found this question -

"1" - - "1";

The result of this statement is 2.

Can anyone explain what is going on here?

I also found that with even - the addition of strings take place but with odd - subtraction. This only happens when a number is a string.

Here are some more eamples-

"1" - "1" => 0
"1" - - "1" => 2
"1" - - - "1" => 0
"1" - - - - "1" => 2
"a" - "b" => NaN
2
  • 3
    1 - - 1 == 1 - (-1) == 1 + 1 ... doing a - on a string will coerce the string to a Number Commented Oct 31, 2017 at 2:21
  • Not what you're asking about, but as a natural next step you may like to read about the unary plus operator. +"1" + +"1" => 2, but "1" + "1" => "11". Commented Oct 31, 2017 at 2:27

2 Answers 2

6

As per ecma script spec :

12.8.4 The Subtraction Operator ( ‐ )

5. Let lnum be ToNumber(lval).

6. Let rnum be ToNumber(rval).

7. Return the result of applying the subtraction operation to lnum and rnum

What that means In case of subtraction both operands are converted to a number.

So "1" - "1" actually means ToNumber("1")- ToNumber("1") but in +, since it's "overloaded" (as java guy would call it), it goes to "concatenation in case of string.

Sign up to request clarification or add additional context in comments.

Comments

2

The expression is equivalent to "1" - (-"1"). The unary minus will convert its argument ("1") to a number (1) and take its inverse (-1). The binary minus will convert its arguments ("1" and -1) to numbers (1 and -1) and compute their difference (2).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.