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

3
  • 1
    What do you mean "why"? Per e.g. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 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. Commented Dec 24, 2017 at 13:11
  • Empty arrays are falsy in PHP but this is JavaScript and it has its own rules. Commented Dec 24, 2017 at 13:14
  • Same question. You can find the answer here stackoverflow.com/questions/19146176/… Commented Oct 19, 2022 at 20:13

3 Answers 3

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,

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.