DEV Community

Discussion on: Day 2 Learning Javascript

Collapse
 
link2twenty profile image
Andrew Bone • Edited

You can think of modulo like so.
where floor means round down

                       x = 12 % 5
  12 - (floor(12/5) * 5) = 12 % 5
   12 - (floor(2.4) * 5) = 12 % 5
            12 - (2 * 5) = 12 % 5
                 12 - 10 = 12 % 5
                       2 = 12 % 5

More generic example

                       x = a % b 
    a - (floor(a/b) * b) = a % b 

So let's do a random one 34 % 14

                       x = 34 % 14
34 - (floor(34/14) * 14) = 34 % 14
34 - (floor(2.428) * 14) = 34 % 14
           34 - (2 * 14) = 34 % 14
                 34 - 28 = 34 % 14
                       6 = 34 % 14

I don't know if this helps or not 🙂

Collapse
 
amberchisholm profile image
amberchisholm

Wow! I've been going through Stack Overflow and MDN trying to find deeper explanations on this and so far yours is the best breakdown I've seen. The way you explained it definitely makes more sense. So using another example via your method..

26 % 8 = x
26 - (floor(26/8) * 8 = x
26 - (floor(3.25) * 8 = x
26 - (3 * 8) = x
26 - 24 = 2

Is that correct?

Thank you so much for your help!

Collapse
 
link2twenty profile image
Andrew Bone

Yep that's correct, well done 🙂
Glad I could help.