-7

I am new to javascript, and I tried to run the below in Brave browser:

'1' + '2' - 3;

The browser replied with the value 9, which I don't understand.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Atropos
  • 9
  • 5
  • https://github.com/denysdovhan/wtfjs – Dai Oct 13 '21 at 12:15
  • 1
    Because you are adding two strings together "1" + "2" = "12" then Javascript sees you are doing `-2` and treats the left hand side as a number (type coercion), so it becomes `12 - 3` = `9`...not answering officially as this has been answered many times and this Q should be closed. – Halfpint Oct 13 '21 at 12:16
  • `+` is overridden as concatenation for strings but `-` doesn't make sense in string context so JS coerces the string to a number to perform mathematical subtraction. – phuzi Oct 13 '21 at 12:16
  • Thank you all for your comments, got it! – Atropos Oct 13 '21 at 12:33

4 Answers4

2

'1' + '2' is concatenation of strings and result is '12'. '12' - 3 is math operation 12 - 3 and result is 9.

Aleks D
  • 366
  • 5
  • 10
2

You shoud do the intermediate steps and see for yourself.

Try:

a = '1' + '2';
console.log(a);
b = a - 3;
console.log(b);   // prints 9

The + operator is described as for purpose of sum of numeric operands or string concatenation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition

One.Punch.Leon
  • 602
  • 3
  • 10
0

That is because your first two numbers are strings. you would get a correct answer if you used:

1 + 2 - 3

Or if you cannot avoid doing a calculation on a string, convert it to a number first:

parseInt('1') + parseInt('2') - 3
Toiletduck
  • 171
  • 1
  • 13
0

'1'+ '2' = '12' is a string but it is converted to an integer before being substracted by -3, so 12-3.

Taher
  • 11,902
  • 2
  • 28
  • 44
itsmejohn
  • 232
  • 2
  • 7