Beginners Guide To Binary Search In JavaScript

jane venter
2 min readDec 5, 2020

If I want to search for an item in a list, I can check each item from beginning to end, and the most checks I can make is the equal to the length of the list. This is called linear search. I could probably scan my grocery list from beginning to end rather quickly. If I am flipping through each page of a phonebook, however, this is a very inefficient approach to finding a name.

If the list is sorted (like in the phonebook), I can use the binary search algorithm instead. This algorithm involves halving the amount of items we have to search repeatedly until the match is found.

We can write a function to perform a binary search on a sorted array to find a matching element. Let’s talk about what that entails in pseudocode.

There necessitates a starting index and an ending index in order to find the halfway index or midpoint.

Start is equal 0, the first index in the array.

End is equal to the last index in the array, or the length minus one.

We will need to create a loop in order to repeatedly check the midpoint between the start and the end.

Inside the loop we will set the middle to halfway between the start and the end.

We can write a conditional to check if the the element matches the value we are searching for.

If the value found is too large, we must look to the left side of the midpoint and cast away the right half of items in the array .

Therefore we set the end to the middle.

If the value found is too small, we must discard all items to the left of the middle and look to the right.

And we keep going.

An example of what this could look like in JavaScript:

let start = 0;
let end = array.length-1;
while(start < end){
let middle = Math.floor(left + ((right-left)/2))
// I am rounding down so that we are sure to get an integer
if(array[middle] === a){
return middle
}else if(array[middle] < a){
end = middle
}else if(array[middle] > a){
start = middle
}
}
return "not found"
//if start is now equal to end then the item we are searching for is not in the array

--

--