Java Script - Convert To Boolean

Type Conversion

Besides the regular boolean values true and false, JavaScript also treats all other values as either 'truthy' or 'falsy'.

Unless otherwise defined, all values in JavaScript are 'truthy' with the exception of 0, "", null, undefined, NaN and of course false, which are 'falsy'.

We can easily switch between true and false by using the negative operator 1, which will also convert the type to "boolean".

const isTrue = !0;
const isFalse = !1;
const alsoFalse = !!0;

console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

This kind of type conversion can be handy in conditional statements, although the only reason you'd choose to define false as !1 is if you were playing code golf!

Go back