👋 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 [];
}
This works fine in many cases:
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
✅ Perfect.
🐞 Then Comes the Bug
Now try this:
console.log(twoSum([3, 2, 4], 6)); // 🤔
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
, and0
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)) {
✅ 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 [];
}
Now this works:
console.log(twoSum([3, 2, 4], 6)); // [1, 2]
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])
ifkey
can map to0
,false
, or other falsy values. - Use
hasOwnProperty()
or a safer pattern. - JavaScript truthiness is a powerful feature — but can sneak up on you.