DEV Community

Muhammad Hamza
Muhammad Hamza

Posted on

The Sneaky JavaScript Bug That Hides in Plain Sight โ€” A 0 That Broke My Code

๐Ÿ‘‹ Intro

Weโ€™ve all written that handy little twoSum function โ€” loop through an array, find two numbers that add up to a target, return their indices. Easy, right?

Wellโ€ฆ almost.

Recently, while working on a real project, I stumbled into one of JavaScriptโ€™s classic gotchas โ€” and it all came down to a single number: 0.

Letโ€™s break down the bug, the fix, and how you can avoid it in your own code.


๐Ÿง  The Setup: Simple Two Sum

Here's a basic implementation many devs (me included!) start with:

const twoSum = (arr, target)=>{
    const map = {};
    for(let i = 0; i < arr.length; i++){
        const complement = target - arr[i];
        if(map[complement]){
            return [map[complement], i];
        }
        map[arr[i]] = i;
    }
    return [];
}
Enter fullscreen mode Exit fullscreen mode

This works fine in many cases:

console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
Enter fullscreen mode Exit fullscreen mode

โœ… Perfect.


๐Ÿž Then Comes the Bug

Now try this:

console.log(twoSum([3, 2, 4], 6)); // ๐Ÿค”
Enter fullscreen mode Exit fullscreen mode

Expected: [1, 2]
Actual: []

Waitโ€ฆ what?

Hereโ€™s whatโ€™s happening:

  • We store indices in map.
  • When complement = 3, map[3] = 0
  • But then we do: if (map[complement])
  • Since map[complement] = 0, and 0 is falsy in JavaScript, the condition fails.
  • The code skips the match, even though it's correct.

Ouch.


๐Ÿงฏ The Fix: Use hasOwnProperty

Instead of checking if map[complement] is truthy, check if the key exists:

if (map.hasOwnProperty(complement)) {
Enter fullscreen mode Exit fullscreen mode

โœ… Final Working Version:

const twoSum = (arr, target)=>{
    const map = {};
    for(let i = 0; i < arr.length; i++){
        const complement = target - arr[i];
        if(map.hasOwnProperty(complement)){
            return [map[complement], i];
        }
        map[arr[i]] = i;
    }
    return [];
}
Enter fullscreen mode Exit fullscreen mode

Now this works:

console.log(twoSum([3, 2, 4], 6)); // [1, 2]
Enter fullscreen mode Exit fullscreen mode

Boom ๐Ÿ’ฅ


๐Ÿ’ก Takeaway

In JavaScript, 0, null, undefined, false, '', and NaN are all falsy.
So using truthy checks (if (obj[key])) can break your code if the value is legitimately 0 or false.

Always use:

  • if (obj.hasOwnProperty(key)) โ€” โœ… safe
  • Or: if (key in obj) โ€” also works
  • Or even: typeof obj[key] !== 'undefined'

๐Ÿ›  Real-World Use Case

I hit this bug in a small front-end app where I was mapping component state to form field IDs. The field with ID 0 kept getting skipped on validation. Yep โ€” same problem. ๐Ÿ˜…


๐Ÿ“ข TL;DR

  • Avoid if(obj[key]) if key can map to 0, false, or other falsy values.
  • Use hasOwnProperty() or a safer pattern.
  • JavaScript truthiness is a powerful feature โ€” but can sneak up on you.

Top comments (0)