Need help to understand more about Recursion

Hello everyone,

The idea of recursion isn’t something that I can get 100% at the moment, therefore I need some help from you. what I know is that recursion is a loop that happened by calling the argument itself. but I’m not sure what differentiate it from a normal one time calling.

for example, I’m doing an EloquentJS exercise.

Here is the exercise

Define whether a positive whole number is even or odd by:

  • Zero is even.
  • One is odd.
  • For any other number N, its evenness is the same as N - 2.

Define a recursive function isEven corresponding to this description. The function should accept a single parameter (a positive, whole number) and return a Boolean.

This is the solution

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

so my question is why when we input for example 50 it will loop 50-2 until it’s 0 and return true like below? why didn’t it only do it one time so it become 50-2 and return 48?

console.log(isEven(50));
// → true

second question is when we input minus number it will return false.

console.log(isEven(-1));
// → false

I don’t quite understand how the code tells it to return false? because to me if (n < 0) return isEven(-n); looks like it just need to return the minus number itself…

please enlight me…

the function isEven(50) has inside the return isEven(n - 2) so it will call isEven(48), which also has inside return isEven(n - 2) so it will call isEven(46)
Note that if n is 0 or 1 it returns a boolean, but if it’s negative, it returns a function isEven(-n) and, if none of those are true it returns isEven(n - 2), which is a whole other function that does the same checks. It will keep calling a smaller and smaller number until it reaches 1 or 0

that’s not true, it returns false fo odd numbers and true for even numbers

notice you are calling isEven(-n) when a number is negative. That means that if the number is -3 it will call isEven(3) and proceed as if it’s a positive number, if it’s -42 it will call isEven(42) and then prooced as if it’s a positive number resulting in true

1 Like

Hi there, thank you. now that you lay it out like that, I think I see the difference. if we only focus on the last part of the code the difference will be

Recursion

return isEven( n -2);

the output of isEven(50) with this code will be true.

while

Non-recursion

return isEven - 2;

the output of isEven(50) with this code will be 48;

please correct me if im wrong. thank you!

yes, that’s correct 

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.