Hello Campers!
I’ve recently started learning how to use functions in JavaScript. And while learning I also doing some small tasks to ensure I learned the material well. Today I’ve faced with the following task: check whether the number is even or odd using the recursive function. I also have to handle the cases when the number is negative.
Below is the first version, that only handles positive numbers:
let isEven = (num) => {
if (num == 0) return "Number is even";
else if (num == 1) return "Number is odd";
else return isEven(num - 2);
}
console.log(isEven(50));
// → Number is even
console.log(isEven(75));
// → Number is odd
If I pass it negative number I’ll see an error: RangeError: Maximum call stack size exceeded
In order to handle negative numbers I’ve added an additional if statement to the top of the existing one. Here is the code:
// Your code here.
let isEven = (num) => {
if (num < 0) return "Number is negative";
else if (num == 0) return "Number is even";
else if (num == 1) return "Number is odd";
else return isEven(num - 2);
}
console.log(isEven(-50));
// → Number is even
console.log(isEven(75));
// → Number is odd
console.log(isEven(-1));
// → Number is negative
Now I wonder whether is there a way to make this function shorter?
It seems to me, that these part of code:
else if (num == 0) return "Number is even";
else if (num == 1) return "Number is odd";
can be somehow shorthanded. But for now I don’t know how to do that and whether it is possible.
Any ideas?
Link to the challenge with more detailed description: https://eloquentjavascript.net/03_functions.html#i_jxl1p970Fy