Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript for loop variable and recursion

Tags:

javascript

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.

like image 741
mcot Avatar asked Jun 21 '11 00:06

mcot


People also ask

Can you use recursion in a for loop?

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.

Can you do recursion in JavaScript?

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(); // ... }

Which is better for loop or recursion?

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.

Why do we use recursion in JavaScript?

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!


1 Answers

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.

like image 89
MackPro Avatar answered Oct 04 '22 11:10

MackPro