So I have been researching this question for days now and can't seem to find an answer that actually works. I am dealing with an api (trello to be specific) that when providing back json objects places a NULL value in attributes that do not have a value. I am parsing through the data after getting it from the api and need a way to skip the null values or delete them. For example here is a part of an object with a null value:
{ name: 'blah',
due: null,
cards: [ [ [Object], [Object], [Object] ],
[ [Object] ],
[ [Object], [Object], [Object] ],
null,
[ [Object], [Object] ],
[ [Object], [Object], [Object], [Object] ],
[ [Object], [Object] ],
[ [Object], [Object], [Object] ] ] }
The due attribute is used as an override for the date timestamp pulled elsewhere. Right now I am using this which seems to work:
if (!update.due) {
update.lastUpdated = update.history[0].date;
} else {
update.lastUpdated = update.due;
}
Is this the only proper way to check for a null value? its the only way I have found to work consistently. Also, when deleting values from an object is there a way I could check so I could then just remove the attribute altogether?:
"if Obj[attr] === null"
Whether or not you can use the shortcut if (!update.due)
rather than if (update.due !== null)
depends upon the range of values that could be in update.due
and what you want the result of the test to be for that range of values.
In Javascript, you can check for a specific value with ===
or you can allow type conversions with ==
of you can check if any truthy or falsey value.
When you do:
if (!update.due)
you are checking to see if update.due
is any falsey value. Falsey values include null
, ""
, 0
, false
, NaN
, undefined
.
If all you're trying to do is to see if update.due
has some non-zero value numeric or boolean value in it, then if (!update.due)
is compact and does the job just fine.
On the other-hand, if you really want to know unequivocably whether it contains null
or not, then you have to test specifically for null
like this:
if (update.due !== null)
Since if (!update.due)
is shorter, it is very commonly used to just check if there's some defined value in update.due
. You do have to be careful that 0
is not a valid value for you because null
and 0
would give the same result with this particular test. But as long as the values you're testing for would not be empty strings or zero, then if (!update.due)
works just fine.