Home > Tips & Tricks > JavaScript Convert to Boolean in Using !! Operator

JavaScript Convert to Boolean in Using !! Operator

You can convert the value to boolean in javascript using the !! (double exclamation mark) operator. So let’s see how you can convert the value to boolean in javascript?

Convert values to boolean in javascript using the !! operator

In JavaScript, this !! operator referred to as the double negation operator. It may be used by programmers to determine if a variable exists or has a valid value that can be declared true or false.

As a result, utilize a simple !!variable. This can transform the data to a boolean value, which will return false if any of the following values are present: 0,” ”, null, NaN, or undefined. In all other cases, it will return as true.

So let’s see the following hack:

Let’s see with an example.

In the above example, suppose you want to check your account that much money has in your account. So I created the simple functions checkAccount() and console.log the result variable.

So when you run this function with the number then you will get the result cash variable as that ‘number’ and hasMoney variable as ‘true’. If you run this same function with 0 number then it will print the cash as 0 and hasMoney as ‘false’, which means you don’t have money.

How the !! works?

The first ! inverses the value and converts it to a boolean. !value will return false in this situation. So we placed another ! on it to make it true again.

Being Tricky 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment