Addition is not working in JavaScript

One or both of the variables is a string instead of a number. This makes the + do string concatenation.

'2' + 2 === '22';  // true

2 + 2 === 4;  // true

The other arithmetic operators / * - will perform a toNumber conversion on the string(s).

'3' * '5' === 15;  // true

A quick way to convert a string to a number is to use the unary + operator.

+'2' + 2 === 4;  // true

…or with your variables:

+x + +y

Leave a Comment