Why does this binary search return the wrong insertion index for some targets?

I’m using binary search to return the index where a value should be inserted into a sorted array, but some cases come back one position too far left. For example, target 6 should return 3 for [1,3,5,7], but I get 2. What boundary update is wrong here?

function searchInsert(nums, target) {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return lo;
}
console.log(searchInsert([1,3,5,7], 6));

MechaPrime

hi = mid - 1 is the bug.

WaffleFries :grinning_face: