Confusion over Empty Arrays' Truthiness and Equality with False
In JavaScript, empty arrays are considered truthy. However, when compared to the primitive value false, they also evaluate to false. This perplexing behavior can be attributed to the implicit type conversions performed by equality operators.
Let's take a closer look at the example code provided:
var arr = []; console.log('Array:', arr); if (arr) console.log("It's true!"); if (arr == false) console.log("It's false!"); if (arr && arr == false) console.log("...what??");
The first if statement checks if arr is present (as it's an object). Since arr is an Array object, it's present and the condition evaluates to true.
However, the second if statement compares the value of arr (after calling toString()) with the primitive value false. In JavaScript, [] is converted to an empty string ("") when called with toString(), which is considered a falsy value (along with null, undefined, 0, etc.). Therefore, the condition also evaluates to false.
The third if statement combines the previous two conditions using AND operator (&&). Since both arr (now an empty string) and arr == false (true & false) evaluate to false, the entire condition evaluates to false.
In conclusion, empty arrays are truthy in the sense that they are considered present and evaluate to true when used in object or conditional contexts. However, when compared to the primitive value false, they evaluate to false due to implicit type conversions performed by equality operations.
The above is the detailed content of Why Do Empty Arrays Evaluate to Both Truthy and False in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!