Implementing Binary Search in JavaScript
You’re searching through a sorted array of 100,000 product prices. JavaScript’s built-in indexOf() checks every element from the start — that’s potentially 100,000 comparisons. Binary search does it in at most 17. That difference is why the JavaScript binary search algorithm matters, and why it’s worth writing yourself — because JavaScript provides no built-in binary search method.
This article covers how binary search works, how to implement both iterative and recursive versions, and when to use it over linear search.
Key Takeaways
- Binary search only works on sorted arrays and runs in O(log n) time, compared to O(n) for linear search.
- The iterative approach is preferred for most use cases — it’s readable, efficient, and uses O(1) space.
- The recursive version is elegant but consumes O(log n) stack space, and forgetting to
returnthe recursive call is a common bug. - Always sort number arrays with a numeric comparator (
(a, b) => a - b) before applying binary search — JavaScript’s defaultsort()is lexicographic.
What Is Binary Search and Why Does It Require a Sorted Array?
Binary search is a divide-and-conquer algorithm. It works by repeatedly halving the search space until it finds the target value or exhausts all possibilities.
Here’s the catch: it only works on sorted arrays. The algorithm assumes that if the target is greater than the middle element, it must be in the right half. That assumption breaks entirely on unsorted data — you’d get wrong results with no error.
The steps are:
- Find the middle element of the current search range
- If it equals the target, return its index
- If the target is smaller, search the left half
- If the target is larger, search the right half
- Repeat until found or the search range is empty
Implementing Binary Search in JavaScript: Iterative Approach
The iterative version uses a while loop and two pointers. It’s the preferred approach for most cases — readable, efficient, and uses O(1) space.
function binarySearch(arr, target) {
let start = 0
let end = arr.length - 1
while (start <= end) {
const mid = Math.floor((start + end) / 2)
if (arr[mid] === target) {
return mid // Return the index
} else if (arr[mid] < target) {
start = mid + 1 // Search right half
} else {
end = mid - 1 // Search left half
}
}
return -1 // Target not found
}
const prices = [10, 25, 47, 89, 134, 200]
console.log(binarySearch(prices, 89)) // 3
console.log(binarySearch(prices, 50)) // -1
Note that this returns the index of the target, not a boolean. That’s almost always more useful in practice.
Recursive Binary Search in JavaScript
The recursive version passes updated boundary indices on each call. It’s elegant but uses O(log n) stack space — one frame per recursive call.
function binarySearchRecursive(arr, target, start = 0, end = arr.length - 1) {
if (start > end) return -1
const mid = Math.floor((start + end) / 2)
if (arr[mid] === target) return mid
return arr[mid] < target
? binarySearchRecursive(arr, target, mid + 1, end)
: binarySearchRecursive(arr, target, start, mid - 1)
}
const scores = [3, 11, 22, 45, 67, 91]
console.log(binarySearchRecursive(scores, 22)) // 2
console.log(binarySearchRecursive(scores, 50)) // -1
One common bug: forgetting to return the recursive call. Without it, the function returns undefined even when the element exists.
Discover how at OpenReplay.com.
Sorting Before You Search
If your array isn’t already sorted, you need to sort it first. JavaScript’s default Array.sort() sorts lexicographically, which breaks numeric comparisons:
[10, 9, 100].sort() // [10, 100, 9] — wrong
[10, 9, 100].sort((a, b) => a - b) // [9, 10, 100] — correct
Always use a numeric comparator for number arrays before running binary search.
Binary Search vs Linear Search: When to Use Which
| Linear Search | Binary Search | |
|---|---|---|
| Array must be sorted | No | Yes |
| Time complexity | O(n) | O(log n) |
| Best for small arrays | ✅ | ❌ |
| Best for large arrays | ❌ | ✅ |
| Multiple searches | Inefficient | Efficient |
For a 10,000-element array, linear search needs up to 10,000 comparisons. Binary search needs at most 14. If you’re searching once through a small, unsorted array, indexOf() is fine. If you’re searching repeatedly through large sorted data, binary search is the right tool.
Conclusion
Binary search is straightforward to implement in JavaScript once you understand the sorted-array requirement. Use the iterative version by default — it’s cleaner and avoids call stack overhead. Use the recursive version when the structure of your code benefits from it, but remember to always return the recursive call. And always verify your array is sorted with a proper numeric comparator before searching.
FAQs
Yes, binary search works with string arrays as long as they are sorted alphabetically. The comparison operators in JavaScript handle string comparison lexicographically by default, so the same algorithm logic applies. Just make sure the array is sorted using the default sort method, which already sorts strings in lexicographic order.
JavaScript arrays are designed to be flexible and can hold mixed types, which makes a built-in binary search impractical since it requires a sorted, uniformly typed collection. Libraries like Lodash provide sortedIndexOf for this purpose, but for vanilla JavaScript you need to write your own implementation.
The standard implementation returns the index of one matching element, but not necessarily the first or last occurrence. If you need the first or last index of a duplicate value, you must modify the algorithm to continue searching in the left or right half even after finding a match.
Both have the same O(log n) time complexity, so their raw speed is nearly identical. However, the iterative version avoids the overhead of recursive function calls and uses constant memory, making it slightly more efficient in practice. For very deep recursions, the recursive version can also risk a stack overflow.
Complete picture for complete understanding
Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.
Check our GitHub repo and join the thousands of developers in our community.