Mod

You already know +, -, * and /. They're fun and all, but time to get to know %.

It's got a few names from what I can see, and people get very nitpicky about it. You'll hear it called "modulo", "modulus", "the remainder operator", but I like to just call it "mod".

What does it do?

You pass it two numbers, and it gives you whats left after you divide one number by another.

Let's look at some example.

4 % 2;
// returns 0

When you divide 4 by 2, you get exatly 2, with no remainder. The mod operator returns the remainder, so it's 0.

5 % 2;
// returns 1

When you divide 5 by 2, you get 2, with a remainder of 1. The mod operator returns the remainder, so it's 1;

17 % 5;
// returns 2

When you divide 17 by 5, you get 3, with a remainder of 2. The mod operator returns the remainder, so it's 2;

Demo

%

What's it good for?

You might look at this and wonder what the purpose of all this is? But where it comes in handy is when you want to loop through things, like an array of things, or for an animations.

Here's an example of an animation using mod.

See the Pen Using mod for an animation by LoFi (@loficodes) on CodePen.

We keep increasing the value of frame, and then create a value t using %;

const t = (frame % frameCount) / frameCount;

This now gives us a normalised number telling us where we are in the animation.

Using mod for user input to loop through an array works the same way.

See the Pen Choose a Beatle by LoFi (@loficodes) on CodePen.

One thing to be careful of here though is that, when a user decrements a value, if it goes below 0, mod will start returning negative numbers, and in the opposite direction. That's why the function chooseBeatle() has that its if statement.

const chooseBeatle = () => {
  if (currentBeatle < 0) {
    currentBeatle += beatles.length;
  }
  beatle.innerText = beatles[currentBeatle % beatles.length];
};