-1

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
  • 1
    What do you mean *"why"*? Per e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean only zero and `NaN` values, empty strings, `false`, `null` and `undefined` are considered false-y. Other languages make different decisions, e.g. an empty collection is false-y [in Python](https://docs.python.org/3/library/stdtypes.html#truth-value-testing). – jonrsharpe Dec 24 '17 at 13:11
  • Empty arrays are _falsy_ in PHP but this is JavaScript and it has its own rules. – Salman A Dec 24 '17 at 13:14
  • Same question. You can find the answer here https://stackoverflow.com/questions/19146176/why-do-empty-javascript-arrays-evaluate-to-true-in-conditional-structures/73275067#73275067 – Abir Oct 19 '22 at 20:13

3 Answers3

1

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.

TamirNahum
  • 484
  • 2
  • 8
1

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.

elsyr
  • 736
  • 3
  • 9
1

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,

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • I think the "why" here is referring to the decisions behind choosing to make “Boolean([]) === true”, not “where in the spec is this behavior described”. Javascript didn’t just evolve out of the dirt. Someone had to think that an empty array being truthy had advantages over an empty array being falsy. – Brian Schlenker Feb 06 '18 at 06:36