DEV Community

Cover image for NOT NOT, Not Working As Expected
bob.ts
bob.ts

Posted on

2

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (2)

Collapse
 
kaleman15 profile image
Kevin Alemán

Hey! Just a couple of things:

In your example with if ('params' in data) && ('type' in data.params)) { you're missing a ( from the if statement.

The True and False are more python things, maybe you can use true and false.

Good article! Keep it up!

Collapse
 
rfornal profile image
bob.ts

I'll make the adjustments now. Thanks for catching the missing paren.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay