Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  56] [ 7]  / answers: 1 / hits: 80760  / 13 Years ago, wed, march 30, 2011, 12:00:00

Empty arrays are true but they're also equal to false.





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??);





I guess this is due to the implicit conversion operated by the equality operator.



Can anyone explain what's going on behind the scenes?


More From » javascript

 Answers
109

You're testing different things here.



if (arr) called on object (Array is instance of Object in JS) will check if the object is present, and returns true/false.



When you call if (arr == false) you compare values of this object and the primitive false value. Internally, arr.toString() is called, which returns an empty string .



This is because toString called on Array returns Array.join(), and empty string is one of falsy values in JavaScript.


[#93005] Tuesday, March 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenyonc

Total Points: 235
Total Questions: 106
Total Answers: 125

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;