JavaScript

JavaScript

By DeepSource

Operands must both be numbers or strings in addition expressions JS-0377

Anti-pattern

It is recommended to use operands of the same type while adding values as mismatched operand types might result in unexpected output.

When doing addition with operands of different types, the output sometimes results in simple concatenation instead of addition.

Examples

1 + '2' 

While the user may expect this to result in 3 (by integer addition) it will instead result in '12' (by string concatenation) .

Bad practice

var foo = '5.5' + 5;
var foo = 1n + 1;

Recommended

var foo = parseInt('5.5', 10) + 10;
var foo = 1n + 1n;