JavaScript binary search

Binary search discards half of an ascending sorted array after comparing the middle value. low and high are inclusive bounds.

JavaScript
function binarySearch(values, target) {
  let low = 0, high = values.length - 1;
  while (low <= high) {
    const mid = low + Math.floor((high - low) / 2);
    if (values[mid] === target) return mid;
    if (values[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return -1;
}
console.log(binarySearch([2, 4, 6, 8, 10], 8));
console.log(binarySearch([], 8));
if (binarySearch([2, 4], 3) !== -1) throw new Error("missing");
Read the full lesson