Simon Ferndriger
Simon Ferndriger

Reputation: 4962

Is an empty array always interpreted as TRUE?

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

Answers (5)

thefourtheye
thefourtheye

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

Pushker Yadav
Pushker Yadav

Reputation: 856

by default these are things are treated as false in javascript.

  1. false
  2. null
  3. undefined
  4. '' or "" [empty string]
  5. 0 [zero]

Upvotes: 0

Platinum Azure
Platinum Azure

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

vivek_nk
vivek_nk

Reputation: 1600

Yes. Array is an object. So it is true. whereas, null/undefined is false

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Yes. All objects are truthy. Always.

Upvotes: 0

Related Questions