0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program for Binary Search with Example and Explanation

A JavaScript binary search program uses a while loop to repeatedly check the middle element of a sorted array and narrow the search range using low, high, and mid indexes until the target is found or the range is empty; example: function binarySearch(arr, target) { let low = 0, high = arr.length - 1; while (low <= high) { let mid = Math.floor((low + high) / 2); if (arr[mid] === target) return mid; else if (arr[mid] < target) low = mid + 1; else high = mid - 1; } return -1; }.
📋

Examples

Input[1, 3, 5, 7, 9], target=7
Output3
Input[2, 4, 6, 8, 10], target=5
Output-1
Input[10], target=10
Output0
🧠

How to Think About It

To find a number in a sorted list quickly, start by looking at the middle item. If it matches the number, you are done. If the number is smaller, look only in the left half; if larger, look only in the right half. Repeat this process until you find the number or run out of items.
📐

Algorithm

1
Set low to 0 and high to the last index of the array.
2
While low is less than or equal to high:
3
Calculate mid as the middle index between low and high.
4
If the middle element equals the target, return mid.
5
If the middle element is less than the target, set low to mid + 1.
6
Otherwise, set high to mid - 1.
7
If the loop ends without finding the target, return -1.
💻

Code

javascript
function binarySearch(arr, target) {
  let low = 0;
  let high = arr.length - 1;
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return -1;
}

console.log(binarySearch([1, 3, 5, 7, 9], 7)); // 3
console.log(binarySearch([2, 4, 6, 8, 10], 5)); // -1
console.log(binarySearch([10], 10)); // 0
Output
3 -1 0
🔍

Dry Run

Let's trace searching for 7 in [1, 3, 5, 7, 9] through the code

1

Initialize pointers

low = 0, high = 4 (array length - 1)

2

Calculate mid

mid = Math.floor((0 + 4) / 2) = 2, arr[mid] = 5

3

Compare mid value with target

5 < 7, so set low = mid + 1 = 3

4

Calculate new mid

mid = Math.floor((3 + 4) / 2) = 3, arr[mid] = 7

5

Check if found

arr[mid] === target, return 3

lowhighmidarr[mid]action
04255 < 7, set low = 3
34377 == 7, return 3
💡

Why This Works

Step 1: Divide and conquer

The code splits the search range in half each time by calculating the middle index with mid = Math.floor((low + high) / 2).

Step 2: Compare middle element

It compares the middle element to the target using arr[mid] === target to decide if it found the target or needs to search left or right.

Step 3: Adjust search range

If the middle element is less than the target, it moves low up to mid + 1 to search the right half; otherwise, it moves high down to mid - 1 to search the left half.

Step 4: Return result

If the target is found, it returns the index; if the search range is empty (low > high), it returns -1 to indicate the target is not in the array.

🔄

Alternative Approaches

Recursive binary search
javascript
function binarySearchRecursive(arr, target, low = 0, high = arr.length - 1) {
  if (low > high) return -1;
  let mid = Math.floor((low + high) / 2);
  if (arr[mid] === target) return mid;
  else if (arr[mid] < target) return binarySearchRecursive(arr, target, mid + 1, high);
  else return binarySearchRecursive(arr, target, low, mid - 1);
}

console.log(binarySearchRecursive([1,3,5,7,9],7)); // 3
Uses function calls instead of a loop; easier to read but uses more memory due to call stack.
Using built-in Array methods (linear search)
javascript
function linearSearch(arr, target) {
  return arr.indexOf(target);
}

console.log(linearSearch([1,3,5,7,9],7)); // 3
Simple but slower (O(n)) compared to binary search (O(log n)); only good for unsorted or small arrays.

Complexity: O(log n) time, O(1) space

Time Complexity

Binary search halves the search space each step, so it runs in logarithmic time, O(log n), where n is the number of elements.

Space Complexity

The iterative version uses constant extra space O(1) because it only stores a few variables for indexes.

Which Approach is Fastest?

Iterative binary search is fastest and most memory-efficient; recursive uses more space due to call stack; linear search is slowest.

ApproachTimeSpaceBest For
Iterative Binary SearchO(log n)O(1)Large sorted arrays, memory efficient
Recursive Binary SearchO(log n)O(log n)Readable code, small arrays
Linear SearchO(n)O(1)Unsorted or very small arrays
💡
Always ensure the array is sorted before using binary search for correct results.
⚠️
Forgetting to update the low or high pointers correctly, causing infinite loops or wrong results.