First, NOT NOT ...
The single !
converts a value to its truthy or falsey value, which is technically a boolean. But if you need to a real boolean representation of a value for your expression you must convert it to a real boolean value using a double not, !!
.
In my head, I could see the conversion. I hear myself evaluating it as "does this object exist." Knowing that was wrong, I still dug into the code to find out why things were breaking in other areas.
Here's a simple example of the faulty (logic) code.
const data = { params: { type: '' } };
if (!!data.params && !!data.params.type) {
// do something here
}
This code refused to go inside the IF-BLOCK.
After digging into the console, I realized ...
!!data.params
// true
!!data.params.type
// false
What I quickly realized is that I got bit by a simple logic issue. An empty string equates to false
, while a string with something in it equates to true
.
A better set of logic would have been to use the IN
operator.
const data = { params: { type: '' } };
if (('params' in data) && ('type' in data.params)) {
// do something here
}
Then, the inner code for the IF-BLOCK would have worked properly.
Another method that can be used is the hasOwnProperty
method ...
const data = { params: { type: '' } };
if (data.hasOwnProperty('params') && data.params.hasOwnProperty('type')) {
// do something here
}
Generally, I prefer the first of the two solutions. To me, this seems more readable, but that's my preference.