falsey javascript | | Cell 1 | Search

In JavaScript, an empty array [] is considered a truthy value, meaning it's treated as true in a boolean context, resulting in unexpected comparisons when using the loose equality operator ==. This leads to [] == true returning true and [] == false returning false.

Cell 0

console.log([] == true)
console.log([] == false)

What the code could have been:

/**
 * Empty array truthiness check
 */
function checkEmptyArrayTruthy() {
  // Use the Boolean() function to explicitly check the truthiness of the array
  const result = Boolean([]);
  
  console.log(`Empty array truthiness check: ${result}`);
}

/**
 * Empty array falsiness check
 */
function checkEmptyArrayFalsy() {
  // Use the Boolean() function to explicitly check the falsiness of the array
  const result =!Boolean([]);
  
  console.log(`Empty array falsiness check: ${result}`);
}

// Run the checks
checkEmptyArrayTruthy();
checkEmptyArrayFalsy();

// Additional check using the equality operator (only for illustration purposes)
console.log("Empty array == true:", [] == true);
console.log("Empty array == false:", [] == false);

Code Breakdown

Comparison of Empty Array to Boolean Values

console.log([] == true)
console.log([] == false)

Explanation

Output

true
false