How does % sign work in javascript -


this question has answer here:

how % sign work in javascript. following code gives output 0/1.

for(var i= 0; i<10;i++){     console.log(isodd(i))  }  function isodd(num) { return num % 2;}

a%b 

its modulo operator. trys put biggest multiple of b a, returns rest of it:

2%3 /*3 fits 0 times, remainder */ 2 6%5 /* 5 fits once, remainder */ 1 16%5 /* 5 fits 3 times, remainder */ 1 

its useful endless arrays, if go on max index, start again @ 0, can written this:

i++; if(i>=array.length) i=0; 

can shortened to:

i=(i+1)%array.length; 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -