DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for NOT NOT, Not Working As Expected
bob.ts
bob.ts

Posted on

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.

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 Author

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

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await