Technical

Awesome way to convert every type to Boolean on JavaScript

Compare between two variables on JavaScript maybe the thing that every developer has done on their daily work but there is a cool and faster way that you can impress your colleague on doing convert variable to Boolean.

Reverse logical

We are all see the used of reverse logical logic (!) in all of our code base. In JavaScript, this symbol will convert every type into Boolean and then reverse the logic of its operation.

What happen if you use “!!”?

This is tricky now! As I said earlier, JavaScript will cast every operation into Boolean when we attach it with “!”  symbol. And when we attach another “!” logical expression here, we are doing the reverse of reverse of the logical operation thus we converting variable into Boolean type without changing variable context.

Some examples when we only use one “!” logical expression:

!'' // true
!{} // false
!0 // true
!1 // false
![] // false
!undefined // true
!null // true

As you can see on above code, the logical of values were converted into Boolean and then be reversed it conditional evaluation.

So here is what happen when we use two “!” logical expressions:

!!'' // false
!!{} // true
!!0 // false
!!1 // true
!![] // true
!!undefined // false
!!null // false

You can see that the values were converted into Boolean but not changing its conditional expression thus we have success convert the value into Boolean and keep it logical.

Thank you for reading and see you in other articles.