Lessons · JavaScript · Math.floor and %
Whole parts and remainders in JavaScript
JavaScript has no integer division operator: use Math.floor(a / b) for the whole part and a % b for the remainder.
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
Pages from item counts, hours from minutes, cents from dollars, every-Nth-row styling.
How to think about it
How many whole groups, and what is left over? Ask 'how many whole groups' (Math.floor of the division) and 'what is left' (%). Remember % keeps the sign of the left operand.
Worked example
const total = 135;Minutes to h:mm.
const h = Math.floor(total / 60);2.
const m = total % 60;15.
`${h}:${String(m).padStart(2, "0")}`2:15.Your turn
Is n even?
const even = n 2 === 0;
Solve one with the tests running
The trap
7 / 2 is 3.5 in JavaScript. Without Math.floor you will index arrays with 3.5.
Practise Math.floor and % on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.