4 ms·
Thank you! This immediately stood out to me as a clever hack that makes it more complicated than it needs to be. I'd have written this function as: functio
by ChristianBundy 7y ago
Thank you! This immediately stood out to me as a clever hack that makes it more complicated than it needs to be. I'd have written this function as:
function countDownFrom(n) {
console.log(n)
if (n > 0) {
countDownFrom(n - 1)
}
}
This removes both the decrement operator and the return keyword, both of which distract from the concept being taught.
This would also make it simple to add a `step` argument, which could be written as:
function countDownFrom (n, step) {
console.log(n)
if (n > 0) {
countDownFrom(n - step, step)
}
}
- kazinator 7y agocoutDownfrom(n--) contains a pointless assignment to a variable that has no use in the function after the logging call. It's not what I'd call clever. It spoils the teaching value of the solution, because a beginner might be confused into thinking that the mutation of n is essential, like that there is only a single n and it is being stepped to bring about the countdown. The student needs to understand that the countdown occurs even though there are no assignments to n, nor anything imperative other than the side effect of the logging call. Don't write beginner examples which contain red herrings that must be explained away to some of the beginners.
- Fishkins 7y agocountDownfrom(n--) produces infinite recursion, which is arguably why you could call coutDownfrom(--n) clever (you have to understand the subtleties of those operators). I agree that "pointless" or "stupid" are better descriptors, though :)
- rileytg 7y agothe only problem with this approach is it doesn’t clearly teach the concept of a base case and a recursive case
- dev_prashaant 7y agoExactly. That is what I wanted to cover in the blog as well. I could give a better or a difficult example too but that would make it overly complicated which I didn't want it to be.