Check if a number is even or odd

“Even or odd?”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 3: Operators: Math, Comparisons & Logic teaches, and 4 tests check your answer.

The challenge

Write evenOrOdd(n) that returns "even" or "odd". It must work for negative numbers too.

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • evenOrOdd(4) gives "even"
  • evenOrOdd(7) gives "odd"
  • evenOrOdd(0) gives "even"
  • evenOrOdd(-3) gives "odd"

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

The remainder operator % tells you what’s left after dividing by 2.

Hint 2

Careful: -3 % 2 is -1, not 1. Checking n % 2 === 0 avoids that problem.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function evenOrOdd(n) {
  return n % 2 === 0 ? "even" : "odd";
}

Learn what you need

This exercise uses what Grade 3: Operators: Math, Comparisons & Logic teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning