0

I was trying to create a rainbow background using Javascript, and I did find some code that works. The code is:

(function() { // Wrap in a function to not pollute the global scope

    // Colors. These are the color names you can use in CSS. You could use color codes
    // like #rrggbb as well.
    var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
  
    var colorIndex = 0;
  
    setInterval(function(){
      // Set the color and increment the index.
      document.body.style.backgroundColor = colors[colorIndex++];
  
      // Wrap the index if it goes past the length of the array. % is modulo.
      colorIndex %= colors.length;
      }, 1000);
  })();

What does the line colorIndex %= colors.length; do and how does it work?

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
  • 1
    It's a shortcut to `colorIndex = colorIndex % colors.length;`, see [remainder operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder) at MDN. – Teemu Jul 07 '20 at 09:09
  • They are known as short hand operators , you can search using this name for more info :) – Codenewbie Jul 07 '20 at 09:10

1 Answers1

2

Its essentially preventing colorIndex to exceed the colors's array length by setting it back to 0 and again continuing the same. So no matter how big the colorIndex's value get, it will always be less than the color's array length.

And about the syntax, it is just a shortform of

colorIndex = colorIndex % colors.length;
Tushar
  • 602
  • 3
  • 11