1

Following code will output 'true', that means Array() is true. In Python, list() is False, is this just because the language designer's preference?

    document.write("<p>Array() is " + (Array() ? "true" : "false") + "</p>");
Rob Lao
  • 1,526
  • 4
  • 14
  • 38

4 Answers4

6

This is because javascript coerces the value of Array() into a boolean. This is what's referred to as "truthiness", and in javascript, truthy values include any valid object. Array() produces a valid object, and therefore evaluates as a true value in a boolean expression.

Null, undefined, NaN, 0, and the empty string "" evaluate as false.

Why? Because the ECMAScript spec says so.

0

Array() is truthy. In other words, it has a value, and the value is not false, null or undefined. There are many lists of what is truthy and not out there on the web for javascript. Just as an example, a more 'standard'/'accepted' way of creating a new array is by using an array literal - []. If you put this in your console, you'll get "true" as well.

console.log(!!([]));
Stephen
  • 5,362
  • 1
  • 22
  • 33
0

Array() returns array here (though empty), try (Array().length ? "true" : "false")

vladkras
  • 16,483
  • 4
  • 45
  • 55
  • Yes, but you're *still* doing an implicit type conversion here, because `Array().length` is an integer, not a boolean. – kojiro Jul 25 '13 at 04:03
  • @kojiro what's implicit in `.length`? – vladkras Jul 25 '13 at 04:10
  • The question is about implicit Boolean conversion, e.g. *Why is an empty array `false` in one language and `true` in another?* Your answer suggests that instead of one implicit Boolean conversion `Array() ? "true" : "false"` ⇒ `Boolean({}) ? "true" : "false"`, OP should use a *different* implicit Boolean conversion `Array().length ? "true" : "false"` ⇒ `Boolean(0) ? "true" : "false"`. It happens to have a different result because it's a different type conversion, but it's still an implicit conversion. – kojiro Jul 25 '13 at 04:31
  • answer to obvious question, it's different in different languages, because **they're different**, you can use [Array.isArray()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) to get boolean, if you want it so much, but it will also return true. I hope you understan why. – vladkras Jul 25 '13 at 05:05
0

Here Array() is a constructor function that will point to a non-null, defined object even
it would be empty in your example but a valid one and when it will be converted into
boolean,it will be evaluated true (only null and undefined objects are evaluated to
false).

schnill
  • 905
  • 1
  • 5
  • 12