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 😉

Leave a Reply

Your email address will not be published. Required fields are marked *