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)
arr = ...) in Javascript wherever you want, it is quite uncommon within recursive algorithms. Pass the expression as an argument instead (foo(arr.slice(...)))