2

Why does Javascript give an output of 0 when I use the odd operator?

What is the difference between subtraction and addition with a string?

var x = 1;

console.log(x+'1')  // Outputs 11
console.log(x-'1')  // Outputs 0 -- but why?

So how can I do mathematical calculations?

MD Ashik
  • 9,117
  • 10
  • 52
  • 59

3 Answers3

2

The + operator has one of two three meanings in javascript. The first is to add numbers, the second is to concatenate strings. When you do 1 + '1' or '1' + 1 the operator will convert one operand that is not a string to a string first, because one other operand is already evaluated to be a string. The - operator on the other hand has just one purpose, which is to subtract the right operand from the left operand. This is a math operation, and so the JS engine will try to convert both operands to numbers, if they are of any other datatype.

I'm not sure though why typecasting to strings appears to have precedence over typecasting to numbers, but it obviously does.

(It seems to me the most likely that this is a pure specification decision rather than the result of other language mechanics.)

If you want to make sure that the + operator acts as an addition operator, you can explicitly cast values to a number first. Although javascript does not technically distinguish between integers and floats, two functions exist to convert other datatypes to their number equivalents: parseInt() and parseFloat() respectively:

const x = 10;
const result = x + parseInt('1'); // 11

const y = 5;
const result2 = y + parseFloat('1.5'); // 6.5
const result3 = y + parseInt('1.5');   // 6

Edit

As jcaron states in the comment below, the + operator has a third meaning in the form of an unary + operator. If + only has a right operand, it will try to convert its value to a number almost equivalent as how parseFloat does it:

+ '1';     // returns 1
+ '1.5';   // returns 1.5

// In the context of the previous example:
const y = 5;
const result2 = y + +'1.5'; // 6.5

Dhe difference with parseFloat is that parseFloat will create a substring of the source string to the point where that substring would become an invalid numeric, whereas unary + will always take the entire string as its input:

parseFloat('1.5no-longer-valid');   // 1.5
+ '1.5no-longer-valid';             // NaN
JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28
0

That is because + is a concatenation operator. So javascript considers it to be a concatenation operator rather than a mathematical operator.But it is not the case with / ,* ,/ etc.

Mohhamad Hasham
  • 1,750
  • 1
  • 15
  • 18
0

This happens because + its also used to concatenate strings. Then, JS always will find the better way to make the correct typecasts basing on types. In this case, the x+'1' operation, will be identified as string type + string type. Otherwise, x-'1', will become int type - int type.

If you want to work with specific types, try to use type cast conversions, link here.

Abe
  • 1,357
  • 13
  • 31