Why Is Javascript Recursive Function Returning 'undefined' Even When I Am Returning A Value
I am looking at how to implement binary search in a javascript function and found that when I return the value and save it into a variable then when I console.log this comes as und
Solution 1:
You need some return
statements. You could omit the else
statements as well, because if returned, it does not execure the else
part.
constrecursiveBinarySearch = (numbers, target) => {
const midpoint = Math.floor(numbers.length / 2);
if (numbers[midpoint] === target) {
//it does found the value and returnreturn'FOUND';
}
if (numbers[midpoint] < target) {
returnrecursiveBinarySearch(numbers.slice(midpoint + 1), target);
}
returnrecursiveBinarySearch(numbers.slice(midpoint - 1), target);
}
var result = recursiveBinarySearch([1, 2, 3, 4, 6, 8, 100] , 8);
console.log(result); // Here is returning undefined
Post a Comment for "Why Is Javascript Recursive Function Returning 'undefined' Even When I Am Returning A Value"