falsey javascript | Cell 2 | Cell 4 | Search

The JavaScript code console.log(0 || 1) logs the result of the conditional expression 0 || 1 to the console, which evaluates to 1 because 1 is the first "truthy" value encountered. This is due to the || operator's behavior of returning the first truthy value it encounters.

Cell 3

console.log(0 || 1)

What the code could have been:

/**
 * Returns the first truthy value from a list of values.
 * 
 * @param {...any} values - A variable number of values to check.
 * @returns {any} The first truthy value.
 */
function getTruthyValue(...values) {
    // This function uses the short-circuit behavior of || to find the first truthy value
    // It's a more concise and efficient way to do this, but the commented-out version
    // shows how the filter and indexing approach works.
    // return values.filter(Boolean)[0];

    // Instead, we can use the || idiom to simplify the code
    return values.find(Boolean) || null;
}

console.log(getTruthyValue(0, 1));

Code Breakdown

Line 1

console.log(0 || 1)