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
.
console.log([] == true)
console.log([] == false)
/**
* 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);
console.log([] == true)
console.log([] == false)
[]
is considered a truthy value (i.e., it is treated as true
in a boolean context).console.log
statement compares the empty array to true
, which results in a coerced comparison due to JavaScript's loose equality operator. This coercion returns true
.console.log
statement compares the empty array to false
, which also results in a coerced comparison. This coercion returns false
, because in a boolean context, an empty array is considered true
, not false
.true
false