rswerve rswerve - 7 months ago 11
Javascript Question

Return doesn't exit recursive function in javascript

I've read the dozen variations on this question, but those answers haven't led me to what must be an obvious mistake. Why does this always return

false
? Why do I see
called again
even after a
found it
? And if I put a
return
in front of the recursive call, why do I never see
found it
?

function subResult (object, start, target){
console.log('called again')
if (start === target){
console.log('found it')
return true
} else {
for (var i = 0; i < object[start].edges.length; i++){
subResult(object, object[start].edges[i], target)
}
}
return false
}

Answer

Change

for (var i = 0; i < object[start].edges.length; i++){
    subResult(object, object[start].edges[i], target)
}

to

for (var i = 0; i < object[start].edges.length; i++){
    if (subResult(object, object[start].edges[i], target)) {
       return true;
    }
}

I.e. when found your done. If not keep going.