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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3