0

So basically i just started learning JS and had a little exercise which was basically making a function to check if the number is even without using modular arithmetic. When i was done with it i just wanted to compare mine with the answer and i couldn't really get how does it work.

function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);
}

I'm not sure how the part (n-2) works does it somehow puts the number in a loop and basically does n-=2 until the number gets 1 or 0?

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
Marius
  • 59
  • 9

3 Answers3

2

Let's take a look at what is going on behind the scenes when this function is run:

isEven(8)
// isEven(8) Is 8 even?
//   isEven(6)  Is 6 even?
//     isEven(4)  Is 4 even?
//       isEven(2) Is 2 even?
//         isEven(0) Is 0 even? --> Yes, the function immediately returns true
// so I know the one at the top, 8, is even

And so on. For any even number, it eventually gets to 0. For any odd number it eventually gets to 1.

soktinpk
  • 3,778
  • 2
  • 22
  • 33
  • 1
    Note that when the 'bottom' function returns `true`, this is then the result that is returned from the next-to-last function, which is the result returned from the next-to-next-to-last function, on up to the very first. – Phrogz Oct 29 '14 at 02:39
1

If the number is negative, the function makes it positive and runs itself again against the positive value, if it's > 1, it will run itself again until the number is 1 or 0, decreasing the number by 2 on each iteration. It's called recursion.

Lauri Elias
  • 1,231
  • 1
  • 21
  • 25
0

When n <0 it puts a minus before the n in the function and runs it again. If Else then the function is called again but n is decreased by 2. This runs till you get true or false.

CeesJanNolen
  • 76
  • 1
  • 7