skip to Main Content

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


  1. Chosen as BEST ANSWER

    Ok I think I figured out my own question. According to the MDN:

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

    Truthy is defined as

    All values are truthy unless they are defined as falsy. That is, all values are truthy except false, 0, -0, 0n, "", null, undefined, and NaN.

    For context, this is the most popular solution when I look at the solutions list on code wars:

    function oddOrEven(arr) { return arr.reduce((a,b)=>a+b,0) % 2 ? 'odd' : 'even'; }
    

    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.'


  2. The result of % is a reminder and not a boolean value.
    For example:

    if sum = 0
    then sum % 2 === 0
    
    if sum = 1
    then sum % 2 === 1
    
    if sum = 2
    then sum % 2 === 0
    

    Therefore, you should compare the result of % to a specific value if you want to obtain a boolean.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search