falsey javascript | Cell 1 | Cell 3 | Search

This line of code uses the logical OR operator (||) to evaluate two expressions, an empty string ('') and a non-empty string ('unempty strings'). Due to how JavaScript handles falsy values, it will always log 'unempty strings' to the console, regardless of the value of the first expression.

Cell 2

console.log('' || 'unempty strings')

What the code could have been:

/**
 * Returns a non-empty string if the input is truthy, otherwise returns a default message.
 * 
 * @param {string} input - The input string to be evaluated.
 * @returns {string} A non-empty string if input is truthy, otherwise "unempty strings".
 */
function getNonEmptyString(input) {
    if (!!input) { // Check if input is truthy
        return input; // Return the input if it's truthy
    } else {
        return 'unempty strings'; // Return default message if input is falsy
    }
}

// Example usage:
console.log(getNonEmptyString('')); // Output: "unempty strings"
console.log(getNonEmptyString('Hello')); // Output: "Hello"

Code Breakdown

Code Snippet

console.log('' || 'unempty strings')

Explanation