Implementing binary search in JavaScript to return the index if the searched number exist

We are required to write a JavaScript function that takes in a sorted array of numbers as the first argument and a search number as the second argument.

If the search number exists in the array, we need to return its index in the array, otherwise we need to return -1.

We have to do this making use of the binary search algorithm. The binary search algorithm is basically a divide and conquer algorithm which recursively divides the array into halves until it converges to a singleton element.

The sorting of array is necessary for binary search algorithm in this case, as it makes deciding which part to divide easy for us.

How Binary Search Works

Binary search works by comparing the target value with the middle element of the array. If they match, we return the index. If the target is smaller, we search the left half; if larger, we search the right half. This process continues until the element is found or the search space is exhausted.

Binary Search Process -3 -1 4 7 9 11 14 22 left mid right Step 1: Compare target (22) with mid (9) Step 2: 22 > 9, so search right half Step 3: New mid becomes 22, found!

Implementation

const arr = [-3, -1, 4, 7, 9, 11, 14, 22, 26, 28, 36, 45, 67, 78, 88, 99];

const binarySearch = (arr = [], num) => {
    let l = 0;
    let r = arr.length - 1;
    
    while(l 

Output

7
-1
5

Time and Space Complexity

Binary search has a time complexity of O(log n) because we eliminate half of the search space in each iteration. The space complexity is O(1) as we only use a constant amount of extra space for variables.

Aspect Complexity Explanation
Time Complexity O(log n) Search space halved each iteration
Space Complexity O(1) Only uses constant extra variables

Key Points

  • The array must be sorted for binary search to work correctly
  • Binary search is much faster than linear search for large datasets
  • The algorithm works by repeatedly dividing the search interval in half
  • Returns -1 when the element is not found in the array

Conclusion

Binary search is an efficient algorithm for finding elements in sorted arrays with O(log n) time complexity. It's particularly useful for large datasets where linear search would be too slow.

Updated on: 2026-03-15T23:19:00+05:30

694 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements