1

I am practicing using recursive functions to solve some simple javascript problems.

I am running into an issue with the following code,

var locate = function(arr,value){
    for (var i=0; i <arr.length; i++) {
        if(typeof arr[i]=== "string") {
            console.log("string is string");
            if(arr[i]=== value) {
                console.log("This should be true");
                return true;
            }
        }
        else {
            locate(arr[i], value);
        } 
    }
}
console.log(locate(['d', 'a',['e', 'g']], 'e'));

I cannot get this program to return true. It gets to the right part of the code, as it prints the statement above it.

Any help would be appreciated. I have been banging my head at this for a couple of hours now.

Edit-@Matt Burland pointed out the fact that you need to include a return statement when calling the recursive.

2
  • What IS it returning exactly? Commented Oct 27, 2014 at 20:58
  • @LogicArtist: undefined Commented Oct 27, 2014 at 21:02

1 Answer 1

2

When you recurse, you need to return the value returned by the recursive call as you unwind.

So in your else clause, you need:

return locate(arr[i], value);

var locate = function(arr,value){
    for (var i=0; i <arr.length; i++) {
        if(typeof arr[i]=== "string") {
            console.log("string is string");
            if(arr[i]=== value) {
                console.log("This should be true");
                return true;
            }
        }
        else {
            return locate(arr[i], value);
        } 
    }
}
alert(locate(['d', 'a',['e', 'g']], 'e'));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.