Reputation: 4962
Is this the case in all browser versions? Meaning, an empty array is always considered as TRUE and never as FALSE as a boolean representation?
var x = [];
if(x)
alert('this could be an empty array');
else
alert('this could NEVER be an empty array');
Upvotes: 3
Views: 352
Reputation: 239453
According to ECMA Script 5.1 specification's Boolean expression evaluation function, any object will be always evaluated to be Truthy. So, an array will be always evaluated to be truthy.
+-----------------------------------------------------------------------+
| Argument Type | Result |
|:--------------|------------------------------------------------------:|
| Undefined | false |
|---------------|-------------------------------------------------------|
| Null | false |
|---------------|-------------------------------------------------------|
| Boolean | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number | The result is false if the argument is +0, −0, or NaN;|
| | otherwise the result is true. |
|---------------|-------------------------------------------------------|
| String | The result is false if the argument is the empty |
| | String (its length is zero); otherwise the result is |
| | true. |
|---------------|-------------------------------------------------------|
| Object | true |
+-----------------------------------------------------------------------+
As per the last line, for any Object, result will be true
.
Reference: My answer to the other question in SO
Upvotes: 4
Reputation: 856
by default these are things are treated as false in javascript.
Upvotes: 0
Reputation: 46183
Arrays are truthy, yes. If you want an easy way to check for emptiness, use the length
property:
var x = [];
if(x.length)
alert('this array is not empty');
Upvotes: 1
Reputation: 1600
Yes. Array is an object. So it is true. whereas, null/undefined is false
Upvotes: 0