This will be a short post regarding the different ways of returning boolean values in JavaScript, mostly for my own future reference.
In JavaScript, we can invert a value to be truthy or falsy via the logical ! (bang) operator.
!true // false
!false // true
!'test' // false
!'' // true
But if we add another bang operator, we will get the actual boolean value.
!!true // true
!!false // false
!!'test' // true
!!'' // false
We could make use of a Boolean() function to achieve the same result.
Boolean(true) // true
Boolean(false) // false
Boolean('test') // true
Boolean('') //false
There may be times when you need to return a boolean value from a function.
function isString1(someString) {
return someString ? true : false;
// returns true if someString exists and vice versa
}
console.log(isString1('')); // false
console.log(isString1('Boolean String')); // true
or...
function isString2(someString) {
return !!someString
// returns true if someString exists and vice versa
}
console.log(isString2('')); // false
console.log(isString2('Boolean String')); // true
or...
function isString3(someString) {
return !someString
// returns false if someString exists and vice versa
}
console.log(isString3('')); // true
console.log(isString3('Boolean String')); // false
A good example is extending a React component and conditionally rendering an element if a prop exists.
// Contrived example
class OldComponent {
constructor(arg1, arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
}
// Extending OldComponent
class NewComponent extends OldComponent {
constructor(arg1, arg2, arg3) {
super(arg1, arg2);
this.arg3 = arg3;
}
hasArg3() {
return !!this.arg3;
// returns true if arg3 exists and vice versa
}
getArg3() {
if (this.hasArg3()) {
return `${this.arg3} exists!`;
}
}
}
const thisComponent = new NewComponent('Argument 1', 'Argument 2', 'Argument 3');
console.log(thisComponent.getArg3()); // Argument 3 exists!
You can add as many bang operators and Boolean functions as you like. (Why tho?)
Boolean(Boolean(!!!!!(!!!!!(!!!!!'Bang! Bang! Bang!')))) // false