Skip to content

Instantly share code, notes, and snippets.

@coffeejoshua
Created December 24, 2025 21:47
Show Gist options
  • Select an option

  • Save coffeejoshua/a31686ef4617b11d48c892e165c9fed2 to your computer and use it in GitHub Desktop.

Select an option

Save coffeejoshua/a31686ef4617b11d48c892e165c9fed2 to your computer and use it in GitHub Desktop.
My opinion on recursion vs while (in general)
#!/usr/bin/env node
// 0 is even, 1 is odd, and N is even if N-2 is even
/*
Which one is easier to read and understand for you? (Subjectively)
Which one is significantly safer (aka, what could go wrong)? (Objectively)
I found 4 scenarios that would crash the less safe one where the safer one
will return "undefined". Did I miss any?
*/
const recursiveIsEven = function(num) {
// Convert negative numbers to positive
if (num < 0) {
num = -num;
}
if (num == 0) {
return "Even";
}
if (num == 1) {
return "Odd";
}
return recursiveIsEven(num - 2);
};
const whileIsEven = function(num) {
// Convert negative numbers to positive
if (num < 0) {
num = -num;
}
while (num >= 0) {
if (num == 0) {
return "Even";
}
if (num == 1) {
return "Odd";
}
num = num -2;
}
};
console.log(recursiveIsEven(9));
console.log(recursiveIsEven(-14));
console.log(whileIsEven(9));
console.log(whileIsEven(-14));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment