title: How to calculate modulo of negative integers in JavaScript?
body: <p>I'm trying to iterate over an array of jQuery objects, by incrementing or decrementing by 1. So, for the decrementing part, I use this code:</p>
  
  <pre><code>var splitted_id = currentDiv.attr('id').split('_');
  var indexOfDivToGo = parseInt(splitted_id[1]);
  indexOfDivToGo = (indexOfDivToGo-1) % allDivs.length;
  var divToGo = allDivs[indexOfDivToGo];
  </code></pre>
  
  <p>so I have 4 elements with id's:</p>
  
  <pre><code>div_0
  div_1
  div_2
  div_3
  </code></pre>
  
  <p>I was expecting it to iterate as
  3 - 2 - 1 - 0 - 3 - 2 - etc..</p>
  
  <p>but it returns -1 after the zero, therefore it's stuck. So it iterates as:</p>
  
  <p>3 - 2 - 1 - 0 - -1 - stuck</p>
  
  <p>I know I can probably fix it by changing the second line of my code to</p>
  
  <pre><code>indexOfDivToGo = (indexOfDivToGo-1 + allDivs.length) % allDivs.length;
  </code></pre>
  
  <p>but I wonder why JavaScript is not calculating negative mods. Maybe this will help another coder fellow too.</p>