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…