DEV Community

June Dang
June Dang

Posted on

3

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay