Quantcast
Channel: Andela
Viewing all articles
Browse latest Browse all 615

Javascript convert to boolean using !!(double bang)operator

$
0
0

Every value has an associated boolean, true or false, value in JS. For example, a null value has an associated boolean value of false. A string value, such as abc has an associated boolean value of true.

Values that are associated with boolean true are said to be truthy. Values that are associated with boolean false values are said to be falsy.

A full list of truthy values can be found here:

Truthy

A full list of falsy values can be found here:

Falsy

A single “!” symbol in javascript, also called a “bang”, is the logical “not” operator. If you place this operator in front of a boolean value, it will reverse the value, returning the opposite.

!true; // Returns false.
!false; // Returns true.



If a bang (“!”) returns the opposite truthy value, what would a bang executed twice on a value do?

const x = true; // Associated with true.
const a = !x; // The returns the opposite of 'x', false.
const b = !a; // The ! takes value 'a' of false and reverses it back to true.

!!true // Evaluates to true.
!!false // Evaluates to false.

So, running a bang twice determines the opposite of value, and then returns the opposite of that.

With non-boolean values, it is kind of cool to see what the double bang does:

const x = 'abc'; // Associated with true.
const a = !x; // The ! determines x is associated with true and returns the opposite, false.
const b = !a; // The ! takes value 'a' of false and reverses it to true.

!!'abc' // Evaluates to true.
!!null // Evaluates to false.

Knowing the associated boolean value of any given value is helpful if you want to quickly reduce a value to a boolean:

function BankAccount(cash) {
this.cash = cash;
this.hasMoney = !!cash;
}
var account = new BankAccount(100.50);
console.log(account.cash); // 100.50
console.log(account.hasMoney); // true

var emptyAccount = new BankAccount(0);
console.log(emptyAccount.cash); // 0
console.log(emptyAccount.hasMoney); // false

In this case, if an account.cash value is greater than zero, the account.hasMoney will be true.

Let’s see another example:

const userA = getUser('existingUser'); // { name: Abel, status: 'lit' }
const userB = getUser('nonExistingUser'); // null

const userAExists = !!userA; // true
const userBExists = !!userB; // false

The post Javascript convert to boolean using !!(double bang)operator appeared first on Andela.


Viewing all articles
Browse latest Browse all 615

Trending Articles