Lessons · TypeScript · adding two numbers
Plain addition
With two numbers, + adds. The surprises come only when one side is a string, and from floating point, as in every language.
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
Totals, counters, coordinates: addition is everywhere, and knowing the two ways it can surprise you covers most numeric bugs in the browser.
How to think about it
Keep numbers as numbers all the way through. For money, work in whole cents; for display, round at the end with toFixed.
Worked example
console.log(2 + 3);5.
console.log(2 + 3 * 4);14: multiplication first.
console.log(0.1 + 0.2);0.30000000000000004: floats, as in every language.
console.log((0.1 + 0.2).toFixed(2));0.30: round for display, never in the middle of a calculation.
Your turn
The sum of a and b.
const sum = a b;
Solve one with the tests running
The trap
+ is the only arithmetic operator that also joins strings. If a total comes out as text, one operand arrived as a string.
Practise adding two numbers on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.