Boolean-ish
So what is the output here?
console.log("to be" || "not to be");
Explanation
The value "to be"
is evaluated to "true." The OR logical operator returns the first operand if that operand is evaluated to be true.
Boolean-ish: truthy or falsy values!
- If a value can be converted to true, the value is so-called truthy.
- If a value can be converted to false, the value is so-called falsy.
0
,NaN
,null
,undefined
, empty string (""
or''
or``
) are all falsy.- All other values are truthy.
Logical operators (as well as if/loop conditions) embrace Boolean-ish!
console.log(null && "Ali"); // null evaluates to false console.log(undefined || "Ali"); // undefined evaluates to false console.log(!"Ali"); // "Ali" evaluates to true
The Boolean-ish is embraced by the JavaScript community too. For instance, it is common to see code like this
if (user) { // Skipped if user is undefined or null
}
Which can easily be converted to
if (user !== undefined && user !== null) {
}
Another everyday use is to set a default value to a function argument.
function calcWage (hoursWorked, hourlyPayRate) {
hourlyPayRate = hourlyPayRate || 12.5;
// calculate the wages!
}
calcWage(40); // uses default hourly pay rate.
calcWage(35, 15);
Which can easily be avoided by using default function parameters! (We will cover functions in a future chapter.)
function calWage (hoursWorked, hourlyPayRate = 12.5) {
// calculate the wages!
}
My advice is to avoid tricky or hacky expressions! Code what you mean! Especially when it is not much more work to do so.
There are cases where it might be more work; for example, the following expression
query = query && query.trim() || "";
does the job of the code below:
if (query !== undefined && query !== null) {
query = query.trim(); // removes whitespace from both ends
} else {
query = "";
}
Here is another one:
denominator = denominator || 1;
which does the job of the following code:
if (
denominator === undefined ||
denominator === null ||
Number.isNaN(denominator) ||
denominator === 0
) {
denominator = 1;
}