Check if a number is divisible by another in JavaScript
Beginner · 4 min read
"Does this number divide evenly by that one?" is one of the most common questions in code. It decides which table rows get a stripe, whether a year is a leap year, and which items in a list get a separator. It is also the heart of FizzBuzz, the classic beginner puzzle.
In this tutorial you will write a helper, divisibleBy(n, d), then use it to label the numbers 1 to 15 as fizz, buzz, fizzbuzz or the number itself. You will also find out what happens when the divisor is zero. You need to know %, the remainder operator, and the ? : operator, which picks one of two values.
Divisible means "no remainder"
n is divisible by d when d fits into n an exact number of times, with nothing left over. The % operator gives what is left over, so the test is "is the remainder zero?"
console.log(15 % 3); // 0: 15 divides by 3
console.log(16 % 3); // 1: one left over
The FizzBuzz rules
For each number from 1 to 15:
- If it divides by both 3 and 5, write
fizzbuzz. - Otherwise, if it divides by 3, write
fizz. - Otherwise, if it divides by 5, write
buzz. - Otherwise, write the number.
A number that divides by both 3 and 5 is a number that divides by 15.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
25 Divisibility
easyWrite divisibleBy(n, d), then label 1 to 15 as fizz, buzz, fizzbuzz or the number itself. Then check what your helper says about a divisor of zero.
Stuck? Three hints, smallest first
- 1. Divisible means the remainder is exactly zero.
- 2. Check the combined case first, or 15 is labelled
fizzand neverfizzbuzz. - 3.
n % 0isNaN, andNaN === 0isfalse, so nothing is divisible by zero.
Step 1: the helper
const divisibleBy = (n, d) => n % d === 0;
console.log(divisibleBy(15, 3), divisibleBy(15, 5)); // true true
console.log(divisibleBy(16, 3), divisibleBy(16, 5)); // false false
console.log(divisibleBy(-9, 3)); // true
n % d === 0 is already true or false, so the arrow function returns it directly. A negative number works too: -9 % 3 is -0, and -0 === 0 is true.
Step 2: the label, in the wrong order
The rules list fizz before buzz, so it is tempting to check 3 first. The ? : operator reads like "if this, then that, else ...", and you can chain it:
const labelTry = (n) =>
divisibleBy(n, 3) ? 'fizz'
: divisibleBy(n, 5) ? 'buzz'
: divisibleBy(n, 15) ? 'fizzbuzz'
: String(n);
console.log(labelTry(15)); // fizz, but it should be fizzbuzz
15 divides by 3, so the first check catches it and the fizzbuzz branch never runs. This bug only shows up on one line in fifteen, so it is easy to miss.
Step 3: most specific first
Move the combined check to the top:
const label = (n) =>
divisibleBy(n, 15) ? 'fizzbuzz'
: divisibleBy(n, 3) ? 'fizz'
: divisibleBy(n, 5) ? 'buzz'
: String(n);
console.log(label(15), label(9), label(10), label(7)); // fizzbuzz fizz buzz 7
The rule to remember: when one condition is a special case of another, test the special case first. String(n) turns the number into text, so every label is a string.
Step 4: label 1 to 15
Array.from({ length: 15 }, ...) makes a list of 15 items. The function you pass gets each position i, from 0 to 14, so i + 1 counts from 1 to 15:
const labels = Array.from({ length: 15 }, (_, i) => label(i + 1));
console.log(labels.join(' ')); // 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz
The _ is a name for the first argument, which we don't need. join(' ') puts the labels on one line with spaces between them.
Step 5: zero, on both sides
What does the helper say about dividing by zero?
console.log(7 % 0); // NaN
console.log(divisibleBy(7, 0)); // false
console.log(divisibleBy(0, 7)); // true
7 % 0 is NaN, "Not a Number", and NaN === 0 is false. So nothing counts as divisible by zero, and the helper doesn't crash. That safety is a lucky side effect, not a design, so it is worth knowing.
The other way round, 0 % 7 is 0, so zero is divisible by every number. That is correct maths, but it can surprise you in a form check like "quantity must be a multiple of 6".
Step 6: the school rules agree
You may remember shortcuts from school. A number divides by 3 if its digits add up to a multiple of 3, and by 5 if it ends in 0 or 5. % agrees with both:
console.log(12345 % 3 === 0, (1 + 2 + 3 + 4 + 5) % 3 === 0); // true true
console.log(1230 % 5 === 0, 1234 % 5 === 0); // true false
The full solution
The answer panel defines divisibleBy and label, builds the fifteen labels, and prints the zero and digit-rule cases. The checks underneath confirm every label, and that nothing divides by 0 while 0 divides by everything. Press Run to see the output.
const divisibleBy = (n, d) => n % d === 0;
const label = (n) =>
divisibleBy(n, 15) ? 'fizzbuzz'
: divisibleBy(n, 3) ? 'fizz'
: divisibleBy(n, 5) ? 'buzz'
: String(n);
const labels = Array.from({ length: 15 }, (_, i) => label(i + 1));
console.log('15 by 3 and 5 :', divisibleBy(15, 3), divisibleBy(15, 5));
console.log('16 by either :', divisibleBy(16, 3), divisibleBy(16, 5));
console.log('-9 by 3 :', divisibleBy(-9, 3));
console.log('7 by 0 :', divisibleBy(7, 0), '<- 7 % 0 is', 7 % 0);
console.log('labels :', labels.join(' '));
console.log('digit-sum rule for 3 on 12345:', 12345 % 3 === 0, (1 + 2 + 3 + 4 + 5) % 3 === 0);
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.
test('15 divides by both 3 and 5', [divisibleBy(15, 3), divisibleBy(15, 5)], [true, true]);
test('16 divides by neither', [divisibleBy(16, 3), divisibleBy(16, 5)], [false, false]);
test('a negative divides the same way', divisibleBy(-9, 3), true);
test('everything divides by 1', divisibleBy(7, 1), true);
test('and nothing divides by 0', divisibleBy(7, 0), false);
test('zero is divisible by everything', divisibleBy(0, 7), true);
test('the fifteen labels', labels, ['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz', '13', '14', 'fizzbuzz']);
test('the digit-sum rule for 3 agrees with the remainder', [12345 % 3 === 0, (1 + 2 + 3 + 4 + 5) % 3 === 0], [true, true]);
test('and the last-digit rule for 5 does too', [1230 % 5 === 0, 1234 % 5 === 0], [true, false]);
Order of tests is the whole exercise. Checking 3 before 15 means 15 never reaches its own branch, and the bug is invisible until you look at exactly one line of output. Test the most specific condition first — or derive the label by concatenation, which removes the ordering question entirely.
divisibleBy(7, 0) returning false rather than throwing is worth knowing: 7 % 0 is NaN, and NaN === 0 is false, so the helper is accidentally safe. divisibleBy(0, 7) is true, which is mathematically correct and occasionally surprising in a validation.
Common mistakes
- Checking 3 before 15. 15 is labeled
fizzand neverfizzbuzz. Test the most specific case first. - Writing
n % d == 1for "not divisible". The remainder can be 2, 3 or more. Usen % d !== 0. - Forgetting that 0 divides by everything.
divisibleBy(0, 7)istrue. If zero shouldn't pass, check for it separately.
Try it yourself
- Extend FizzBuzz with a fourth word,
bazz, for multiples of 7. What should 105 print? - Build the labels by joining strings instead: start with
'', add'fizz'if divisible by 3 and'buzz'if divisible by 5. Why does this remove the ordering problem? - Write
isMultipleOf6(n)that also refuses 0.