Arrays and algorithms · intermediate
JavaScript Program for Binary Search
Implement binary search in JavaScript on a sorted array, watch the search range halve in the visualizer, and compare it with indexOf() and findIndex().
- while loop
- Math.floor()
- sorted arrays
- indexOf()
Binary search finds a value in a sorted array by checking the middle element and discarding the half that cannot contain the target. Each step halves the range, so a million elements need at most 20 comparisons, while indexOf() may need a million.
The program
function binarySearch(items, target) {
let low = 0;
let high = items.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (items[mid] === target) return mid;
if (items[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
const numbers = [3, 8, 15, 23, 42, 57, 71, 89];
console.log(binarySearch(numbers, 42));
console.log(binarySearch(numbers, 10));4
-1How it works
- low and high are the first and last positions that could still hold the target.
- mid is the middle position; Math.floor() keeps it a whole index.
- If the middle value is too small, only the right half can contain the target, so low moves past mid; otherwise high moves before it.
- When low passes high, the range is empty and the function returns -1, like indexOf().
Watch it run line by line
Search for 42 and watch low, mid and high close in: mid is 3 (23), then 5 (57), then 4, the answer. Searching for 10 shows low and high crossing.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Built-in searches (linear)
indexOf() and findIndex() check elements one by one, so they work on unsorted arrays but are slower on large sorted ones. includes() answers just yes or no.
const numbers = [3, 8, 15, 23, 42, 57, 71, 89];
console.log(numbers.indexOf(42), numbers.includes(10));
console.log(numbers.findIndex((n) => n > 50));4 false
5Common mistakes
- Running binary search on an unsorted array: it returns wrong answers without any error.
- Using while (low < high), which misses the target when it is the last remaining element.
- Setting low = mid instead of mid + 1, which can loop forever.
Try it yourself
- Count the comparisons and compare them with a linear search on 1,000 numbers.
- Return the position where the target would be inserted when it is missing.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.