luthien
luthien

Reputation: 1305

Recursive use of Javascript returns undefined

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)

Upvotes: 0

Views: 48

Answers (2)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

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);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

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)

Upvotes: 4

Related Questions