I am going through JavaScript: The Definitive Guide. In it it says
Boolean([]) // => true
But I don't understand the logic behind this. Why is the boolean of an empty array true?
I am going through JavaScript: The Definitive Guide. In it it says
Boolean([]) // => true
But I don't understand the logic behind this. Why is the boolean of an empty array true?
Array is considered as an object, even if it's empty. That's why the Boolean has a value, means it's true.
Only false, null or undefined are values which will return false.
JavaScript (and other languages) have a concept of 'truthy' and 'falsey' values.
You said you're from a C++ background, so we can make it analogous to something like this in C++:
if (ptr) { }
which is falsey if ptr is null, and truthy otherwise.
It just so happens that in JavaScript, arrays - even empty ones, among many other things - are considered to be truthy.
The ECMAScript specification defines how values are cast to booleans, per the abstract ToBoolean operation: https://www.ecma-international.org/ecma-262/6.0/#sec-toboolean
That operations includes a single entry for object input:
Object: Return
true.
Thus, when you supply any object to Boolean, including an array (even an empty one), you'll get a true value back,