I'm trying to delete the object properties that don't evaluate to true. What am I doing wrong?
The problem is that you're using the "identity" or "strict equality" operator: ===
instead of the normal "equality" operator: ==
. You aren't allowing the program to do any sort of finagling when you ask it "are these two things the same?".
Here's some examples:
1 == 1 // true
"1" == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
0 == undefined // false
null == undefined // true
vs:
3 === 3 // true
3 === '3' // false!
When you write ... === false
, the only time that will "evaluate to true" is when the variable is actually equal to false
. It won't "evaluate to true" if the variable was null
or undefined
.
See this question for even more detail on the problem:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Just changing the ===
operator to ==
isn't going to solve things, either. You're going to have to more closely match the problem definition, and check if things don't evaluate to true.
This "evaluates to true" concept is so common in JS that they built it straight into their flow control statements, like if
and while
:
if (... something that evaluates to true ...) {
// ... do something
}
while (... something that evaluates to true ...) {
// ... do something
}
If you combine this with the logical not operator, then you can use this same "evaluates to true" check to find things that don't evaluate to true:
if (!object[key]) {
delete object[key];
}
This is the "right" way to do things in Javascript (or at least the most "canonical").