New course! Every coder should learn Generative AI!
Try a free lesson0
Javascript Recursion
Very simply, what is javascript recusion? More specifically, Can anyone show some small code snippets where it could be applied(please do not use the factorial, egg chicken: thanks 😐), and where not, with an explanation of why
3 Answers
+ 1
First off: Anything you can do with recursion you can do without and the other way around, so pick what works best. Some examples:
Say you have some function that takes 2 numbers a and b and you want to make sure a is always smaller than b:
function something(a, b){
if(a > b) return something(b, a);
// do something
}
Not saying it's good practice but I've seen it a lot.
Say you have a function that sends money but you can only send 1000€ max:
function send_money(amount){
while(amount > 1000){
send_money(1000);
amount -= 1000;
}
// send the rest of the money
}
Those are some of the more simple examples; more typical examples are usually a bit harder.
Say you have a network of cities and you want to visit them all:
function visit(city){
take_photo(city);
for(let neighbor of city.neighboring_cities()){
if(not_seen(neighbor))
visit(neighbor);
}
}
That's venturing into graphs and other data structures though.
(1/2)
+ 3
In general recursive functions tend to be less efficient than non-recursive ones, so if performance is a concern, then you should prefer non-recursion.
Some programming languages try to optimize some recursive functions (tail recursion, stream fusion), but as far as I know Javascript isn't one of them.
A general rule is to worry about performance last, so pick whatever code looks nicer. The third code snippet would look pretty horrible and 3 times as long without recursion, for example: Every city may have many neighbors and each of them has many neigbors and so on, so you get this branching out behaviour; that's where recursion really works well.
(2/2)
+ 2
Schindlabua Thanks.😊😊😊😊