How does %
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;}
How does %
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 the modulo operator. It trys to put the biggest multiple of b into a, then returns the rest of it:
2%3 /*3 fits 0 times, remainder is */ 2
6%5 /* 5 fits once, remainder is */ 1
16%5 /* 5 fits three times, remainder is */ 1
Its really useful for endless arrays, so if you go over the max index, start again at 0, which can be written like this:
i++;
if(i>=array.length) i=0;
Can be shortened to:
i=(i+1)%array.length;