javascript

How to Force A Value Conversion to Boolean in Javascript


In this article, you will learn how to force a value conversion to boolean in Javascript.

Let’s say you have 2 variables.

// A string variable named 'a' with value "codesource"
var a = "codesource";

// An empty string variable named 'b'
var b = "";

In order to force a value conversion to boolean, you can use the double bang operator, !!.

// A string variable named 'a' with value "codesource"
var a = "codesource";

// An empty string variable named 'b'
var b = "";

console.log(!!a);
// => true

console.log(!!b);
// => false

Note: The double bang operator, !! functions by returning the truthy value of its operand. The first ! changes the value into its opposite boolean value. The second ! negates the boolean value taken from the first !.


Share on social media

//