Checking object properties with if (obj[key]) fails when the value is an empty string “”. This post explains why and how to fix it.
Empty Strings Are Falsy
In JavaScript, empty strings are falsy, so they fail truthiness checks:
// All of these are falsy in JavaScript
if ("") { } // false
if (0) { } // false
if (null) { } // false
if (undefined) { } // false
if (false) { } // false
if (NaN) { } // false
The Bug
Scenario: You have a configuration object where some values are intentionally empty strings:
const userPreferences = {
username: "john_doe",
theme: "", //Empty string
language: "en",
notifications: "" // Empty string
};
//WRONG: This fails for empty strings!
function applyPreferences(preferences, defaults) {
const merged = { ...defaults };
Object.keys(preferences).forEach(key => {
if (merged[key]) { //Fails for "theme" and "notifications"!
console.log(`${key} already set`);
} else {
// This overwrites even though the key exists with empty string!
merged[key] = preferences[key];
}
});
return merged;
}
Solution: Check Key Existence, Not Value Truthiness
Use one of these to check if a key exists:
Option 1: The in Operator (Recommended)
// CORRECT: Checks if key exists, regardless of value
if (key in obj) {
console.log('Key exists');
} else {
obj[key] = defaultValue;
}
Why it works:
- in checks for key existence, not value truthiness
- Works for “”, 0, false, null, undefined
Option 2: hasOwnProperty()
//CORRECT: Also checks key existence
if (obj.hasOwnProperty(key)) {
console.log('Key exists');
} else {
obj[key] = defaultValue;
}
Option 3: Check for “undefined” Explicitly
//CORRECT: Explicitly checks if value is undefined
if (obj[key] !== undefined) {
console.log('Key exists');
} else {
obj[key] = defaultValue;
}
Comparison Table
| Method | Empty String “” | 0 | false | null | undefined | Missing Key |
|---|---|---|---|---|---|---|
| if (obj[key]) | ❌ Fails | ❌ Fails | ❌ Fails | ❌ Fails | ❌ Fails | ✅ Works |
| key in obj | ✅ Works | ✅ Works | ✅ Works | ✅ Works | ✅ Works | ❌ Fails |
| obj.hasOwnProperty(key) | ✅ Works | ✅ Works | ✅ Works | ✅ Works | ✅ Works | ❌ Fails |
| obj[key] !== undefined | ✅ Works | ✅ Works | ✅ Works | ✅ Works | ✅ Works | ❌ Fails |
Key Takeaways
- Empty strings are falsy in JavaScript
- Use key in obj or obj.hasOwnProperty(key) to check key existence
- Don’t rely on truthiness checks when empty strings are valid values
- Test with edge cases: “”, 0, false, null, undefined
- Be explicit about what you’re checking: existence vs truthiness
- Consider the context: empty strings might be intentional values
When empty strings are valid, check for key existence, not just value truthiness. This prevents subtle bugs and makes your code more robust.