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.
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.
'1' + '2'
is concatenation of strings and result is '12'.
'12' - 3
is math operation 12 - 3 and result is 9.
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
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