I have an issue where I have recursion inside of a for loop:
function func(node) {
for(var i = 0; i < node.children.length; i++) {
func(node.children[i]);
}
}
Obviously because JavaScript does not have block scope, the same i variable is getting modified each time the function is called. What is the best way to remedy this? Assume regular EcmaScript 3 and I can't use JavaScript 1.7 "let".
I know this has been asked before, but the other questions don't seem to show recursion, they show one function call where a closure could be used.
You surely can use loops in a recursive function. What makes a function recursive is only the fact that the function calls itself at some point in its execution path. However you should have some condition to prevent infinite recursion calls from which your function can't return.
Introduction to the JavaScript recursive functions And this technique is called recursion. Suppose that you have a function called recurse() . The recurse() is a recursive function if it calls itself inside its body, like this: function recurse() { // ... recurse(); // ... }
Recursion has more expressive power than iterative looping constructs. I say this because a while loop is equivalent to a tail recursive function and recursive functions need not be tail recursive. Powerful constructs are usually a bad thing because they allow you to do things that are difficult to read.
Recursion is when a function calls itself until someone stops it. If no one stops it then it'll recurse (call itself) forever. Recursive functions let you perform a unit of work multiple times. This is exactly what for/while loops let us accomplish!
Cache the length of the array so you would have the following:
function recurse(node) {
for(var i = 0, count = node.children.length; i < count; i++) {
recurse(node.children[i]);
}
}
You should always cache especially when you're dealing with HTMLCollections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With