Searching..

How to binary search in JS

Stephan Bakkelund Valois
3 min readJul 30, 2020

The binary search will search through a sorted dataset. It’s important that the data is sorted from the lowest to the highest value, or else the binary search wouldn’t work. If your data isn’t sorted, you need to sort it before you can search over it with binary search.

The binary search is of O(log n) complexity. which basically means it will cut the data in half with each iteration, until it finds the target value we’re searching for. It will actually be much faster the more data it has to search through, compared to for example a linear search, which would search from the start of the data, and all the way through the data until the target value was found. If you are unfamiliar with algorithms and time complexity, you can check my other blog post How Algorithms And Big O Notation Works. In An Understandable Way.

To execute a binary search, we first need to figure out the start, and the end of our data:

const array = [1, 2, 3, 4, 5, 6];
let lowPointer = 0;
let highPointer = array.length - 1;

We set the lowPointer to 0, which will point at index 0 in our array. We set the highPointer to the last index in our data.

Next up is to calculate the midPointer:

const midPointer = Math.floor(highPointer + lowPointer) / 2);

--

--