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.
Spot the Bug answer: The function incorrectly returns ‘false’ when a duplicate is found, but it should return ‘true’ to indicate a duplicate exists.
The fix:
Change ‘return false;’ to ‘return true;’ inside the if block.
Why:
The function’s name ‘hasDuplicate’ implies it should return true if a duplicate is present. The current logic returns false immediately upon finding a duplicate, which is the opposite of the expected behavior. If no duplicates are found after checking all elements, it correctly returns true, which is also incorrect for that scenario.