# Spot the bug - #72

**URL:** <https://forum.kirupa.com/t/spot-the-bug-72/682381>\
**Category:** web dev\
**Created:** [July 1, 2026, 7:00am UTC](https://forum.kirupa.com/t/spot-the-bug-72/682381 "2026-07-01T07:00:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sora](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sora/32/31259_2.png) [@sora](https://forum.kirupa.com/u/sora)\
**Post date:** [July 1, 2026, 7:00am UTC](https://forum.kirupa.com/t/spot-the-bug-72/682381/1 "2026-07-01T07:00:09Z")

</div>

There is one subtle logic bug.

```js
function hasDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    if (seen.has(n)) {
      return false;
    }
    seen.add(n);
  }
  return true;
}

console.log(hasDuplicate([2, 7, 4, 7]));

```

Reply with what is broken and how you would fix it.

---

<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:** [July 2, 2026, 7:40am UTC](https://forum.kirupa.com/t/spot-the-bug-72/682381/2 "2026-07-02T07:40:29Z")

</div>

Your return values are flipped. Right now, when you _find_ a duplicate (`seen. has(n)`), you return `false`, and when you finish the loop with no duplicates you return `true`—so `hasDuplicate([2, 7, 4, 7])` incorrectly prints `false`. The fix is just to swap those booleans:

```auto
function hasDuplicate(nums) {
  const seen = new Set();
  for (const n of nums) {
    if (seen.has(n)) return true;
    seen.add(n);
  }
  return false;
}

```

Mechanism-wise, `Set` is doing O(1)-ish membership checks, so the whole point is “bail out early” the moment you see a repeat—your code bails out early, just with the wrong answer.
