NOT NOT, Not Working As Expected

rfornal

bob.ts

Posted on September 14, 2020

NOT NOT, Not Working As Expected

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
}
Enter fullscreen mode Exit fullscreen mode

This code refused to go inside the IF-BLOCK.

After digging into the console, I realized ...

!!data.params
// true

!!data.params.type
// false
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Generally, I prefer the first of the two solutions. To me, this seems more readable, but that's my preference.

💖 💪 🙅 🚩
rfornal
bob.ts

Posted on September 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

NOT NOT, Not Working As Expected
javascript NOT NOT, Not Working As Expected

September 14, 2020