(Source code is at https://github.com/jauyeunggithub/rook-hotel-answers/blob/master/q2.txt)
The modulo operator (%) in JavaScript lets us get the remainder when we divide one number by the other.
In this article, we’ll look at how to use modulo operator (%) in JavaScript.
How to use modulo operator (%) in JavaScript?
We can use the modulo operator to get the remainder of the left operand divided by the right one.
For instance, we write:
const numFn = (num) => {
if (num % 14 === 0) {
console.log('foobar')
return
} else if (num % 7 === 0) {
console.log('foo')
return
} else if (num % 2 === 0) {
console.log('bar')
return
}
console.log('NUMBER')
}
We check if num
can be divided by 14 evenly with num % 14 === 0
.
If it is, we log 'foobar'
.
Similarly, we do the same checks when dividing num
by 7 and 2 and log different values.
Otherwise, we log 'NUMBER'
if none of the conditions are true
.
Conclusion
We can use the modulo operator to get the remainder of the left operand divided by the right one.