154

How can I use modulo operator (%) in calculation of numbers for JavaScript projects?

1
  • 1
    Someone might want to rename this question from modulo to remainder because it pops up in Google searches for a modulo operator in JS. Commented Jul 2, 2024 at 20:02

1 Answer 1

255

It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:

10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.

Apparently it is not the same as the modulo operator entirely.

Sign up to request clarification or add additional context in comments.

8 Comments

You can fit 3 exactly 3 times in 9. If you would add 3 one more time to 9, you would end up with 12. But you were dividing 10, so instead you say it's 3 times 9 with the remainder being 1. That's what modulo gets you.
I think it is better to explain it this way: Modulo is the difference left when dividing a value. You can use this to calculate listing lists with items, for example: 10 % 10 gives you 0. When it is 0 you know there a 10 items in a list. For example 20 % 10 gives you the same value, 0, another 10 items in a list......
There is no "integer division" operator in JS AFAIK; 10 / 3 will result in 3.333.... You need to truncate the fraction, for instance by using Math.floor().
@MDeSchaepmeester, well it kind of is using the same basic operator as in other languages, but it lacks a specific integer primitive. JS natively only has "number" primitives which are floating-point, and thus there also are no integer-only operators.
@Paul Redmond, because you can't fit 2 into 1 (= 0 times). This gives the remainder 1.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.