-1

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 undefined.

const recursiveBinarySearch = (numbers, target) => {
    const midpoint = Math.floor(numbers.length / 2);

    if (numbers[midpoint] === target){
        //it does found the value and return
        return 'FOUND';

    } else if(numbers[midpoint] < target) {
        recursiveBinarySearch(numbers.slice(midpoint+1), target);

    } else {
        recursiveBinarySearch(numbers.slice(midpoint-1), target);

    }
}
var result = recursiveBinarySearch([1, 2, 3, 4, 6, 8, 100] , 8);
console.log(result); // Here is returning undefined

Thanks in advance.

3
  • 6
    Missing return statements? Commented Nov 29, 2019 at 13:31
  • 4
    you don't return the result of the recursion. Commented Nov 29, 2019 at 13:34
  • After all these years doing javascript I couldn't get my head around on that if you don't return the result of the recursive function this one will return undefined, it is not easy to see at first but something to keep in mind. Commented Nov 29, 2019 at 13:52

1 Answer 1

3

You need some return statements. You could omit the else statements as well, because if returned, it does not execure the else part.

const recursiveBinarySearch = (numbers, target) => {
  const midpoint = Math.floor(numbers.length / 2);

  if (numbers[midpoint] === target) {
    //it does found the value and return
    return 'FOUND';

  }

  if (numbers[midpoint] < target) {
    return recursiveBinarySearch(numbers.slice(midpoint + 1), target);
  }

  return recursiveBinarySearch(numbers.slice(midpoint - 1), target);
}
var result = recursiveBinarySearch([1, 2, 3, 4, 6, 8, 100] , 8);
console.log(result); // Here is returning undefined

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

3 Comments

Why do you always answer questions that should be closed instead? Is it for the reputation? Or do you not know the reasons for closing questions?
the rep does not matter, but it is easier to show what is going wrong, than to add a comment. anway i expect that the question is being deleted at the end.
I'll certainly be voting to delete it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.