This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the algorithms category.
Last Updated: 2024-11-23
I had a function to delete empty strings in JavaScript.
for (let [key, value] of Object.entries(userInput)) {
if (value && value == "") {
delete userInput[key]
}
}
When I ran it with the object {"key1": "something", "key2": ""}
, it did not
remove key2
. Why?
The issue was that if (value)
returns false because empty strings in JS are falsey.
The fix:
if ((typeof value !== 'undefined') && value == "") {
}
In general, the rules for falsity are subtle and vary between every language. The safest thing to do is to explicitly check for presence or emptiness instead.