Sometimes, we may see that if we use the +
operator to add 2 numbers with JavaScript that they’re concatenated instead of being added together.
In this article, we’ll look at why using the +
operator will concatenate the 2 numbers instead of adding them together.
One or More of the Operands aren’t Numbers
The reason that adding 2 numbers together in JavaScript is that one or more of the operands that we try to add together may not be numbers.
Therefore, we should make sure that they’re both numbers before trying to add them.
To do this, we can convert to numbers with various functions or operators.
For instance, we can write:
const y = '1'
const z = '2'
const x = +y + +z;
console.log(x)
to use the unary + operator to convert y
and z
to numbers.
Therefore, x
is 2 since we add the numbers 1 and 2 together.
Another way to convert the operands to numbers is to use the Number
function.
For instance, we can write:
const y = '1'
const z = '2'
const x = Number(y) + Number(z);
console.log(x)
Number
returns the number converted from the argument, so we get the same value for x
as the previous example.
Another function we can use to convert non-numbers to numbers is the parseInt
function.
It’ll convert non-numbers to integers.
For example, we can write:
const y = '1'
const z = '2'
const x = parseInt(y, 10) + parseInt(z, 10);
console.log(x)
The first argument is the non-number value to convert.
And the 2nd argument is the base of the number to convert the number to.
10 means we convert it to a decimal number.
Conclusion
To make sure that we’re adding 2 values together instead of concatenating them with the JavaScript + operator, we should convert the values to numbers before trying to add them.