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>");
3
  • Helpful answer: stackoverflow.com/questions/10440792/… Commented Jul 25, 2013 at 3:55
  • it looks like low understanding of JS Objects Commented Jul 25, 2013 at 4:22
  • @MuthuGanapathyNathan that's about python Commented Oct 3, 2024 at 23:49

4 Answers 4

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.

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

Comments

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(!!([]));

Comments

0

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

4 Comments

Yes, but you're still doing an implicit type conversion here, because Array().length is an integer, not a boolean.
@kojiro what's implicit in .length?
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.
answer to obvious question, it's different in different languages, because they're different, you can use Array.isArray() to get boolean, if you want it so much, but it will also return true. I hope you understan why.
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).

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.