I am trying to exit a function call when a value is found, and I can not wrap my head around this.
Using the debugger I've noticed that the return found; line makes execution jump to the end of the function, OK... but after that another iteration on the for loop is started.
I've tried using break too.
My code is below.
Edited
I've checked the logic on the debugger, adding a breakpoint on found = true and it works fine, so the only thing left is that it should exit properly after that...
// Tree traversal until answer found via answer.id
function locateAnswer(wholeTree, answerID) {
var found = false;
if (wholeTree.answers) { // checks if next_queston is populated first
for (var i = 0; i < wholeTree.answers.length; ++i) {
if (wholeTree.answers[i].id == answerID) {
console.log("found!");
found = true;
return found; // TRIED break; TOO
} else {
for (var j = 0; j < $scope.breadcrumbs.length; ++j) {
if ($scope.breadcrumbs[j].question == wholeTree.question) {
// if already exist, we pop elements until it does not exist anymore
while ($scope.breadcrumbs[j]) {
$scope.breadcrumbs.pop();
}
}
}
// we push the new breadcrumb
$scope.breadcrumbs.push({ "question": wholeTree.question, "answer": wholeTree.answers[i].answer });
locateAnswer(wholeTree.answers[i].next_question, answerID);
}
}
}
// ALSO TRIED return HERE AFTER break
};
returnshould work.