falsey javascript | Cell 0 | Cell 2 | Search

In the given code breakdown, console.log() prints output to the console, while the OR operator (||) returns the first truthy value from its operands. In JavaScript, empty arrays ([]) are considered falsy values, whereas non-empty arrays (['not falsey enough']) are considered truthy values.

Cell 1

console.log([] || ['not falsey enough'])

What the code could have been:

/**
 * Returns a non-empty array or a default value if the provided array is empty.
 *
 * @param {Array} array - The input array to check.
 * @param {Array} [defaultArray=['not falsey enough']] - The default array to return if the input array is empty.
 * @returns {Array} A non-empty array or the default array.
 */
function getNonEmptyArray(array, defaultArray = ['not falsey enough']) {
  // Check if the array is truthy and has at least one element
  if (array && array.length > 0) {
    // If the array is truthy, return it
    return array;
  } else {
    // If the array is empty, return the default array
    return defaultArray;
  }
}

// Usage example
console.log(getNonEmptyArray([])); // Output: ['not falsey enough']
console.log(getNonEmptyArray(['hello', 'world'])); // Output: ['hello', 'world']

Code Breakdown