DEV Community

Discussion on: Recursion Explained (with Examples)

Collapse
 
postcapital profile image
James Carter

It's good to know you can do all recusive algorithms iteratively also, I had always wondered.
Your example above does not iterate unless you change n > 1 not n < 1, it had me going for a bit you and should always test your code ;-)

function factorial(num) {
let total = 1;
for(let n = num; n > 1; n--) {
total *= n;
}
return total;
}

Collapse
 
christinamcmahon profile image
Christina

Oops, thanks for pointing that typo out, I've made the change in the post.