## DEV Community is a community of 719,546 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Mohit Bajoria

Posted on

# Binary Search in JavaScript

• Binary search works on sorted arrays.
• Binary search begins by comparing an element in the middle of the array with the target value.
• If the target value matches the element, its position in the array is returned.
• If the target value is less than the element, the search continues in the lower half of the array. If the target value is greater than the element, the search continues in the upper half of the array.

By doing this, the algorithm eliminates the half in which the target value cannot lie in each iteration.

A quick implementation of binary search in JavaScript

Let say's we have a array and we want to search for `7` and return it's index #### Iterative Solution

``````function BinarySearch(arr, value) {
let start = 0;
let end = arr.length - 1;

while (start <= end) {
let mid = Math.floor((start + end) / 2);

if (value === arr[mid]) {
return mid;
}
if (val < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}

return -1;
}
``````

#### Recursive Solution

``````function BinarySearch(arr, value, start = 0, end = arr.length - 1) {
let mid = Math.floor((start + end) / 2);

if (arr[value] === mid) {
return mid;
}

if(start >= end) {
return -1
}

return value < arr[mid] ? BinarySearch(arr, value, start, mid - 1) : BinarySearch(arr, value, mid + 1, end)
}

``````

Thanks