Using ! ans !! to convert values to boolean

·

2 min read

You might come across coercing the value to a boolean using the two logical NOT operators while working on JavaScript. In this blog let us understand how it works. In Javascript, all values are either truthy or falsey.

so if our datatype does not contain anything in it it is considered falsely otherwise. Here are a few examples,

let x;

x = "Mathematics";  // truthy
x = "";             // falsy
x = {};             // truthy
x = 0;              // falsy

Using the logical NOT operator (!), we can convert a truthy value to false and a falsy value to true

let x;

x = !"Mathematics";  // false
x = !"";             // true
x = !{};             // false
x = !0;              // true

{} an empty object is not falsy because on string coercion it gives '[object Object]'.

You might come across a situation where you want to use a non-boolean value as a boolean. A double NOT (!!) allows us to succinctly convert a non-boolean value to its corresponding boolean value.

let x;

x = !!"Ecstasy";     // true
x = !!"";            // false
x = !!{};            // true
x = !!0;             // flase

Note that !! is not an operator––it's just two logical NOT operators chained together. In fact, we can use as many !s as we like.
we generally use the !! in a function if we want to ensure returns a boolean value.

And it's worth noting that using the built-in Boolean function does the same thing as !! and is arguably more readable and easier to understand.

let x;

x = !!"" === Boolean("");                        // true
x = !!"Mathematics" === Boolean("mathematics");  // true