3

I am trying to loop an array using a recursive function. The loop should stop and return the value of the key, if it matches a given regex pattern.

The loop stops correctly when the condition is met. However, it only returns the key's value if the match occurs for the first key (index 0) in the array and returns 'undefined' for the rest.

Where's my mistake? Here's the code to better illustrate:

    function loop(arr,i) {
  var i = i||0;
  if (/i/gim.test(arr[i])){
    console.log("key value is now: " + arr[i])
    return arr[i]; // return key value
  }
  // test key value
  console.log("key value: " + arr[i]); 

  // update index
  i+=1; 

  // recall with updated index
  loop(arr,i); 
}

console.log( loop(["I","am", "lost"]) ); 
// "key value is now: I"
// "I" <-- the returned value

console.log(  loop(["am", "I", "lost"])  ); 
// "key value: am" 

// "key value is now: I" <-- test log 
// undefined <-- but the return value is undefined! why?!

1 Answer 1

7

You have to return the value from the recursive call,

  // recall with updated index
  return loop(arr,i); 
}

The final call for the function loop will return a value, but the other calls for the same function returns undefined. So finally you end up in getting undefined

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

5 Comments

Thanks @rajaprabhu !
@ingo Glad to help! Try to press the tick mark present inside this answer, if you thinks that this answer has helped you. But this is not a compulsion. :)
I've done it. :) Unfortunately my low reputation level restricts my up vote to be publicly displayed.
@ingo Haven't you notice a tick mark? Not the upvote. :)
I need glasses... :) Thanks again!

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.