Help me understand recursion in JavaScript

Status
Not open for further replies.

rtstyk

Ars Scholae Palatinae
1,236
This is someone else's code which I'm trying to modify to make it not use global variable. I've been pulling my hair though unable to make this work.

The original code is:

http://jsfiddle.net/t4p9G/

The code uses global variable 'body' which I'm trying to avoid. The function does not use 'return' statement.

Code:
var body = '';

function scan(obj)
{
    var k;
    if (obj instanceof Object) {
        for (k in obj){
            if (obj.hasOwnProperty(k)){
                body += 'scanning property ' + k + '<br/>';
                scan( obj[k] );  
            }                
        }
    } else {
        body += 'found value : ' + obj + '<br/>';
    };
  
};

scan(testJSON);

document.getElementById('output').innerHTML = body;

I tried to modify this to not use global variable and use return statement but it doesn't then walk all the nodes. It seems to stop after finding the first value:

http://jsfiddle.net/t4p9G/62/

Code:
function scan(b, obj)
{
    var k;
    if (obj instanceof Object) {
        for (k in obj){
            if (obj.hasOwnProperty(k)){
                b += 'scanning property ' + k + '<br/>';
                return scan(b, obj[k] );  
            }                
        }
    } else {
        return b+'found value : ' + obj + '<br/>';
    };
  
};

var body='';
var body= scan(body, testJSON);

document.getElementById('output').innerHTML = body;

Why is that? What am I missing?
 

dragonlord

Ars Scholae Palatinae
1,123
[url=http:/civis/viewtopic.php?p=25384013#p25384013:33ycjz2t said:
Mile Zero[/url]":33ycjz2t]You're returning too early. Don't return inside your for...in loop, return after it. Otherwise, as soon as you hit an own property, you're returning out of the loop, and never getting to the next property.

This :)

Seriously, if this is the first time you've really looked into recursion then take comfort in the fact that it's a really easy mistake to make.

You may also want to make a 2 member structure or something else that you can pass by reference would make your life easier by being able to apply your results to the object and return a boolean from the function.

quick google search found this - http://www.javascriptkit.com/javatutors ... klJpEAQ30Z

you can then create an object with the results and pass it around your method and if you need to terminate when you find the first one you can set the function to return true if it finds something or the call to the function returns true and return false at the end of the function in case nothing was found.
 
Status
Not open for further replies.