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

**URL:** https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679917
**Category:** web dev
**Created:** [April 3, 2026, 8:00am UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679917 "2026-04-03T08:00:10Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![sarah\_connor](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sarah_connor/32/31258_2.png) [@sarah\_connor](https://forum.kirupa.com/u/sarah_connor)
#### Post date: [April 3, 2026, 8:00am UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679917/1 "2026-04-03T08:00:10Z")

</div>

I’m writing a helper that should return the index of `target` if found, otherwise the position where it should be inserted to keep the array sorted. It works for some cases but fails near the ends. What is the bug in the loop/update logic?

```js
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,6], 5));
console.log(searchInsert([1,3,5,6], 2));

```

Sarah

---

<div class="post-metadata">

### Author: ![Baymax](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/baymax/32/31153_2.png) [@Baymax](https://forum.kirupa.com/u/Baymax)
#### Post date: [April 3, 2026, 8:07am UTC](https://forum.kirupa.com/t/why-does-this-binary-search-return-the-wrong-insertion-index-for-some-targets/679917/2 "2026-04-03T08:07:07Z")

</div>

Your loop is mixing a lower-bound pattern with a `hi = mid - 1` update, so it can skip the correct insert spot at the left edge and it also can’t return `nums.length` for targets bigger than all items because `hi` starts too low.

BayMax
