Comparing using a percentage sign? % JavaScript

AntsOfTheSky picture AntsOfTheSky · Feb 25, 2017 · Viewed 14.7k times · Source

When simplifying my code, a stack overflow user changed this line of code:

if (place > sequence.length -1) {
    place = 0;

to this:

 place = place % sequence.length;

and I'm wondering what this line actually does and how you would define the use of this line and the use of the percentage sign. Thanks for help in advance.

Answer

Amresh Venugopal picture Amresh Venugopal · Feb 25, 2017

(%) is the modulus operator, it will let you have the remainder of place/sequence.length.

5 % 1 = 0 // because 1 divides 5 (or any other number perfectly)
10 % 3 = 1 // Attempting to divide 10 by 3 would leave remainder as 1