Boolean Evaluation
What is the output here?
console.log("to be" || "not to be"); // to be
Explanation: The value "to be" evaluates to true. The OR logical operator returns the first operand if that operand evaluates to true.
0,NaN,null,undefined, and empty string (""or'') are all falsy.- All other values are truthy.
console.log(null && "Ali"); // null: null evaluates to false
console.log(undefined || "Ali"); // Ali: undefined evaluates to false
console.log(!"Ali"); // false: "Ali" evaluates to true
The JavaScript community uses these Boolean-ish values too. For instance, it is common to see code like this
if (user) {
// Skipped if user is any falsy value (undefined, null, "", 0, false, NaN)
}
That code can be converted to this
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);
That trick can be avoided by using default function parameters. (Default function parameters are covered in the chapter on functions.)
function calcWage(hoursWorked, hourlyPayRate = 12.5) {
// calculate the wages!
}
There are cases where it might be more work; for example, the following expression
query = (query && query.trim()) || "";
does the same job as the code below:
if (query !== undefined && query !== null) {
query = query.trim(); // removes whitespace from both ends
} else {
query = "";
}
Another example:
denominator = denominator || 1;
which does the same job as the following code:
if (
denominator === undefined ||
denominator === null ||
Number.isNaN(denominator) ||
denominator === 0
) {
denominator = 1;
}