131

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

Brett DeWoody
  • 50,328
  • 25
  • 121
  • 168
Ziyaddin Sadigov
  • 7,076
  • 10
  • 31
  • 40

2 Answers2

220

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.

MarioDS
  • 11,911
  • 14
  • 57
  • 114
  • 10
    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. – MarioDS May 12 '13 at 08:38
  • 5
    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...... – Codebeat Mar 05 '14 at 06:43
  • 2
    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()`. – Lucero Aug 20 '14 at 17:02
  • @Lucero you're right, I never realised that! I just assumed it used the same basic operator available in many languages. – MarioDS Aug 20 '14 at 17:31
  • 2
    @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. – Lucero Aug 20 '14 at 21:07
  • @Lucero oh, yes that makes sense! Thanks for the insight. – MarioDS Aug 20 '14 at 21:30
  • Why does 1 % x always return 1? Unless x is less than 1? E.g. 1 % 2 returns 1, why? 1 can't be divided by 2. – Paul Redmond May 18 '16 at 14:52
  • @Paul Redmond, because you can't fit 2 into 1 (= 0 times). This gives the remainder 1. – Conny Olsson Jun 03 '16 at 11:15
  • Thanks! This helped me answer my coding bootcamp's challenge easily. – dex10 Oct 29 '20 at 11:42
8

That would be the modulo operator, which produces the remainder of the division of two numbers.

Joseph
  • 107,072
  • 27
  • 170
  • 214
  • 11
    In C-like languages, including JavaScript, `%` is the remainder operator, not modulo/modulus. They are equivalent for positive values, but different for negative ones. – Aaron Franke Jun 04 '19 at 04:34
  • 2
    downvoting this answer as it doesn't add anything useful to this conversation. – Peter Nov 20 '19 at 17:43