Binary search is one of the most frequently asked topics in coding interviews, and for good reason — it's the classic example of how choosing the right algorithm can turn an O(n) problem into an O(log n) one. Instead of checking every element like a simple loop based linear search would, binary search repeatedly cuts the remaining search space in half.
The only requirement is that the array must already be sorted. On each step, you compare the target with the middle element: if it matches, you're done; if the target is smaller, you discard the right half; if it's larger, you discard the left half. You repeat this until you find the value or run out of elements to check.
Binary Search in JavaScript (Iterative)
function binarySearchIterative(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
return mid; // found — return the index
} else if (arr[mid] < target) {
low = mid + 1; // discard left half
} else {
high = mid - 1; // discard right half
}
}
return -1; // not found
}
const sortedNumbers = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72, 91];
console.log(binarySearchIterative(sortedNumbers, 23));
console.log(binarySearchIterative(sortedNumbers, 100));
Output:
5
-1
Binary Search in JavaScript (Recursive)
The recursive version expresses the exact same idea, but instead of a while loop, the function calls itself with a narrower low/high range each time — a nice example of how recursion can replace iteration when a problem naturally shrinks.
function binarySearchRecursive(arr, target, low = 0, high = arr.length - 1) {
if (low > high) return -1; // base case: search space exhausted
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) return binarySearchRecursive(arr, target, mid + 1, high);
return binarySearchRecursive(arr, target, low, mid - 1);
}
console.log(binarySearchRecursive(sortedNumbers, 91));
console.log(binarySearchRecursive(sortedNumbers, 1));
Output:
10
-1
Both versions run in O(log n) time, since the search space is halved on every step — an array of a million sorted elements takes at most about 20 comparisons. Compare that to a plain linear scan, which runs in O(n) and could take up to a million comparisons in the worst case. The trade-off is that binary search only works on sorted data, so if your array isn't sorted, you need to sort it first (an O(n log n) cost) before binary search's speed pays off — usually worth it if you'll be searching the same array many times.
