A question about modulo

A quick question about modulo in the functions and conditionals challenge part of the course.

The challenge:
Create a function isEven() that takes a number as its only parameter. The function should return true if the number is even and false if the number is odd.

My question is the modulo from my understanding is used to get a remainder of a number, so how is it that the answer to the question makes it only true to even numbers relates to the percentage symbol? I’m just not understanding the function of modulo in this case. Thanks!

let isEven = number => { if (number % 2 == 0) { return true } else { return false } }

even numbers always have a remainder of zero when dividing by two, while even numbers have always a remainder of 1:

console.log(1 % 2) // 1
console.log(2 % 2) // 0
console.log(3 % 2) // 1
console.log(4 % 2) // 0
console.log(5 % 2) // 1
console.log(6 % 2) // 0

Also, the result of comparison is a Boolean so you could simply do:

return number % 2 == 0;
1 Like

When you call the function with a (integer) parameter it divides the number by 2 and the conditional checks if the remainder is 0.

1 Like

Cheers to the answers mentioned by other contributors :grinning_face_with_smiling_eyes:

Just want to add on with a simpler point is, be it ’ zero ’ or ’ more than zero ’ comes from the math division technique since grade school.

Long-Division-Chunking-vs-new-method

(thanks to author for the image)


As for getting even or odd number, you can alter the conditions based on the problem statements you’re facing hence the technique of using modulo is quite flexible and effective for most solutions applied.

Hope this helps

1 Like

Bottom line, we are not dealing with modulo, but remainder. The percent sign % is technically the remainder operator, and that is the expected behavior. Remainders are scalar, modulo is not when we delve into the math.

Historically we have always demonstrated this with long division and the general description…

all values are integers
d : divisor
q : quotient
D : Dividend
R : Remainder

d * q === D - R

R === D - q * r
1 Like

Thank you! A lot of very insightful responses, I understand now!

2 Likes