0

I'm trying to write a recursive function with Javascript, but apparently I miss something and I cannot make it return at the point that I want. In the following example, I would expect to see that baz=18 in the logs, however baz is undefined.

https://jsfiddle.net/n8fg1h3v/1/

Any ideas?

function foo(arr) {
  if (arr[0]==7) {
    return 18
  } else {
    arr = arr.slice(1,arr.length);
    foo(arr);
  }
}

var arr1 = [9,1,2,3,4,7,6];
var baz = foo(arr1);
console.log(baz)
1
  • Please note that while you can make reassignments (arr = ...) in Javascript wherever you want, it is quite uncommon within recursive algorithms. Pass the expression as an argument instead (foo(arr.slice(...))) Commented Jun 1, 2017 at 11:44

2 Answers 2

4

You need a return of calling foo inside of the function.

return foo(arr);

function foo(arr) {
    if (arr[0] == 7) {
        return 18;
    } else {
        arr = arr.slice(1, arr.length);
        return foo(arr);
    }
}

var arr1 = [9, 1, 2, 3, 4, 7, 6];
var baz = foo(arr1);
console.log(baz)

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

2 Comments

do you like to use a default value if no 7 is in the array?
No, this was just a simple example to show and try to understand why my if then else statement with a return inside if did not work as I would have expected. With adding the return foo(arr) as you suggested it works fine in the simple example and also in my real problem. Thanks! (I cannot accept the answer for another ~10 min, I will do it just after that.)
0

I would simply do this:

function foo(arr) {
  var el = arr.find(el => el === 7);  
  return el ? 18 : '7 was not found';
}

var bar = foo([9, 1, 2, 3, 4, 7, 6]);
console.log(bar);

var baz = foo([9, 1, 2, 3, 4, 8, 6]);
console.log(baz);

2 Comments

i would use some, because it breaks the iteration, but it has nothing to do with recursion.
Also Array.prototype.find() breaks the iteration.. I understand your point about recursion, but here I do not think that it's necessary

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.