Hone

Lessons · TypeScript · + with a string and a number

When + stops adding

If either side of + is a string, + joins: '5' + 1 is '51'. Every other arithmetic operator converts to numbers instead.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Form fields and URL parameters are always strings. A total that shows 51 instead of 6 is this bug, and it is the most common JavaScript surprise there is.

How to think about it

Convert at the edge: Number(input) or parseInt as soon as text arrives, then do maths on numbers. If a result looks concatenated, one operand was a string.

Worked example

console.log("5" + 1);
51: one string makes + join.
console.log(5 + 1);
6.
console.log("5" - 1);
4: minus only does maths, so it converts the string.
console.log(Number("5") + 1);
6: convert first when you mean arithmetic.

Your turn

Add one to a typed value.

const total = (input) + 1;

The trap

'5' - 1 is 4 but '5' + 1 is '51'. The asymmetry hides the bug in every operator except the one you use most.

Practise + with a string and a number on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.