Solving a code wars problem and I realized I’m confused how the remainder operator (%) works. Which boolean is returned when you have an expression like 10 % 2
vs 9 % 2
?
Here is the original code wars question:
Given a list of integers, determine whether the sum of its elements is odd or even.
Give your answer as a string matching "odd" or "even".
If the input array is empty consider it as: [0] (array with a zero).
Both of the following solutions seem to work
function oddOrEven(array) {
let sum = array.reduce( (acc, c) => acc + c, 0 )
return sum % 2 ? "odd" : "even"
}
function oddOrEven(array) {
let sum = array.reduce( (acc, c) => acc + c, 0 )
return sum % 2 == 0 ? "even" : "odd"
}
So what exactly does a remainder expression like sum % 2
return? If my understanding of a ternary is correct the remainder expression would have to return true when there is a remainder because the first solution works correctly.
2
Answers
Ok I think I figured out my own question. According to the MDN:
Truthy is defined as
For context, this is the most popular solution when I look at the solutions list on code wars:
And I believe the reason it works is because if a+b % 2 results in 1, and we know 1 is truthy according to the mdn, the ternary expression will return 'odd.' If a+b % 2 results in -1, we also know -1 is truthy per the mdn, so the ternary expression will return 'odd.' If a+b % 2 results in 0, we know 0 is falsy again according to the mdn, so the ternary expression will return 'even.'
The result of
%
is a reminder and not aboolean
value.For example:
Therefore, you should compare the result of
%
to a specific value if you want to obtain aboolean
.