Emmanuel Akinfulubi

JavaScriptMath

Division by zero and remainders in JavaScript

Beginner · 4 min read

When you share 17 sweets between 5 friends, each friend gets 3 and 2 are left over. The 3 is the quotient and the 2 is the remainder. Programs need both all the time: splitting items into pages, turning minutes into hours and minutes, or working out how many buses a group needs.

In this tutorial you will write divide(a, b), which returns both parts as an object, { quotient, remainder }. Then you will see what JavaScript does when you divide by zero, which is not what most people expect. You need to know how to write an arrow function and an object.

JavaScript has no whole-number division

In some languages, 17 / 5 gives 3. In JavaScript, / always gives the exact answer, decimals included:

JavaScript

console.log(17 / 5); // 3.4

To get the whole-number part, you cut off the decimals yourself. Math.trunc does exactly that: it removes everything after the decimal point. "Trunc" is short for truncate, which means cut short.

JavaScript

console.log(Math.trunc(3.4));  // 3
console.log(Math.trunc(-3.4)); // -3

For the remainder, JavaScript has the % operator. 17 % 5 asks "what is left after taking out as many 5s as fit?"

Here is the exercise. If you want to try it on your own first, go ahead. Otherwise, read on and we will build it together.

22 Quotient and remainder, and dividing by zero

easy

Write divide(a, b) returning { quotient, remainder } with an integer quotient. Then check what happens for b of zero.

Stuck? Three hints, smallest first
  1. 1. JavaScript has no integer division operator; Math.trunc(a / b) is it.
  2. 2. % gives the remainder that matches a truncating division.
  3. 3. Division by zero does not throw: it gives Infinity, -Infinity or NaN.

Step 1: the divide function

Put the two pieces together. The arrow function returns an object, so the object is wrapped in round brackets. Without them, JavaScript would read the { as the start of a function body.

Step 1

const divide = (a, b) => ({ quotient: Math.trunc(a / b), remainder: a % b });
console.log(divide(17, 5)); // { quotient: 3, remainder: 2 }

There is a simple way to check the answer: the parts should rebuild the original. Five times 3 plus 2 is 17.

JavaScript

console.log(5 * 3 + 2); // 17

Step 2: negative numbers

Now try a negative dividend. The dividend is the number being divided, here -17.

Step 2

console.log(divide(-17, 5)); // { quotient: -3, remainder: -2 }
console.log(5 * -3 + -2);    // -17

Math.trunc cuts toward zero, so -3.4 becomes -3. The remainder comes out as -2, and the pair still rebuilds -17. That rebuild is the whole reason to use Math.trunc with %: they are designed as a matched pair.

Step 3: the floor wrong turn

Math.floor also removes decimals, so it is tempting to use it instead. On positive numbers it gives the same answer. On negatives, it rounds down, away from zero:

Step 3

console.log(Math.floor(-17 / 5)); // -4
console.log(5 * -4 + -2);         // -22, not -17

With Math.floor, the quotient is -4, but % still gives -2, and the pair no longer adds up. If you ever want floor division, you need a different remainder to match it. A later exercise builds that helper.

Step 4: dividing by zero

In maths, dividing by zero has no answer. Many languages stop the program with an error. JavaScript doesn't. It gives back a special value instead:

Step 4

console.log(1 / 0);  // Infinity
console.log(-1 / 0); // -Infinity
console.log(0 / 0);  // NaN
console.log(5 % 0);  // NaN

Infinity is a real number value in JavaScript, bigger than every other number. NaN means "Not a Number", the result of a calculation that makes no sense.

Because nothing is thrown, the bad value travels on through your code. Imagine a dashboard showing total / count as a percentage. When count is 0, the page shows "Infinity%". The safe habit is to check the divisor before you divide, for example count === 0 ? 0 : total / count.

Step 5: rounding up for containers

Sometimes you need the opposite of truncating. If 145 passengers need 40-seat buses, 3 buses aren't enough:

Step 5

console.log(145 / 40);            // 3.625
console.log(Math.ceil(145 / 40)); // 4

Math.ceil rounds up to the next whole number ("ceil" is short for ceiling). Any time the question is "how many boxes, pages or trips do I need?", Math.ceil is the tool.

The full solution

The answer panel builds divide, runs it on positive and negative numbers, compares it with Math.floor, prints the division-by-zero results and solves the bus question. The checks underneath confirm every value, including that each quotient and remainder rebuild the original number. Press Run to see the output.

The answer

const divide = (a, b) => ({ quotient: Math.trunc(a / b), remainder: a % b });

console.log('divide(17, 5)   :', divide(17, 5));
console.log('divide(-17, 5)  :', divide(-17, 5), '<- trunc, so -3 remainder -2');
console.log('rebuild         :', 5 * -3 + -2);
console.log('floor would give:', Math.floor(-17 / 5));
console.log('1 / 0           :', 1 / 0, ' -1 / 0:', -1 / 0, ' 0 / 0:', 0 / 0);
console.log('5 % 0           :', 5 % 0);
console.log('how many 40-seat buses for 145 passengers:', Math.ceil(145 / 40));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('17 into 5 goes 3 times with 2 left over', divide(17, 5), { quotient: 3, remainder: 2 });
test('the two parts rebuild the original', 5 * 3 + 2, 17);
test('a negative dividend truncates towards zero', divide(-17, 5), { quotient: -3, remainder: -2 });
test('and that pair still rebuilds it', 5 * -3 + -2, -17);
test('floor would have given -4 instead', Math.floor(-17 / 5), -4);
test('dividing by zero gives an infinity, it does not throw', [1 / 0 === Infinity, -1 / 0 === -Infinity], [true, true]);
test('but 0 / 0 is NaN', Number.isNaN(0 / 0), true);
test('and any remainder by zero is NaN', Number.isNaN(5 % 0), true);
test('ceil is what "how many containers" needs', Math.ceil(145 / 40), 4);

Math.trunc(a / b) and a % b are a matched pair: they satisfy b * q + r === a for negative operands too, which is what makes the rebuild assertion hold. Swapping in Math.floor breaks that pairing — you would need the floored remainder from exercise 24 to match it.

The silent infinities are the practical hazard. A rate of total / count with count of zero gives Infinity, which then renders as "Infinity%" on a dashboard, or as null once it passes through JSON. Guard the divisor rather than the result.

Common mistakes

  • Expecting / to drop the decimals. 17 / 5 is 3.4. Use Math.trunc(a / b) for the whole-number part.
  • Mixing Math.floor with %. On negative numbers they don't match, so the quotient and remainder stop rebuilding the original.
  • Waiting for an error on division by zero. JavaScript returns Infinity or NaN instead. Check the divisor before dividing.

Try it yourself

  1. Use divide to turn 135 minutes into hours and minutes. You should get 2 hours and 15 minutes.
  2. Change divide so it returns null when b is 0.
  3. A list has 23 items and shows 10 per page. Work out the number of pages with Math.ceil, then check it by hand.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.