Ad space (banner)
🟨JavaScript Lessons
Lesson 34 / 69

The Binary Search Algorithm

In this lesson you'll learn the binary search algorithm so you can understand how to efficiently find a target value in already-sorted data. This is for people searching "JavaScript binary search implementation" or "algorithm what is binary search."

Binary search is an algorithm for efficiently finding a target value in already-sorted data. Picture "opening a dictionary, checking around the middle, and narrowing the range in half each time." Compared to checking one item at a time from the start (linear search), it finds the target value overwhelmingly faster the more data there is.

The sample code manages the search range using two indices, low and high, and compares the middle value mid against the target value target. If the target is larger, the lower half of the range is discarded; if smaller, the upper half is discarded — so the range to check gets cut in half with each comparison. If it's never found, it returns -1.

A common beginner stumbling block is the precondition that the target data must already be sorted. Using binary search on an array that isn't sorted won't give correct results. Also be careful: getting the update of low and high wrong leads to an infinite loop.

As a foundation of data structures and algorithms, this is a classic subject that shows up frequently in coding tests for job interviews. In large-scale systems handling millions of records, the speed of binary search really makes an outsized difference.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)