Rob Lao
Rob Lao

Reputation: 1623

javascript why Array() is true?

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>");

Upvotes: 1

Views: 163

Answers (4)

schnill
schnill

Reputation: 955

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

Upvotes: 0

user2498534
user2498534

Reputation: 76

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.

Upvotes: 6

vladkras
vladkras

Reputation: 17228

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

Upvotes: 0

Stephen
Stephen

Reputation: 5460

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

Upvotes: 0

Related Questions