4m1r
4m1r

Reputation: 12542

A Better Way to Try / Check array length in Javascript?

What would be a better way to try checking that response is an array with length?

try{
    response.errors.length > 0;
    deferred.reject(response)
}
catch(e){
    deferred.resolve(response);
}

Upvotes: 1

Views: 1666

Answers (5)

user2246674
user2246674

Reputation: 7719

The length check (length > x) will not throw an exception. What might throw an exception is if response or errors evaluates to undefined (e.g. doesn't exist).

if (response && response.errors && response.errors.length) {
  // Have errors
  // The check for response might not be needed, but one should most
  // definitely ensure that `response.errors` evaluates to an object (Array?)
  // before trying to access a property upon it.
}

Note that this uses && short-circuiting behavior.

Alternatively, sometimes it's nice to normalize data (assumes response is always an object). In this case we make sure that we have an "empty array" as needed such that we have some array on which to check the length.

response.errors = response.errors || []
if (response.errors.length) {
   // Have errors
}

In the above examples I also utilize that a non-0 number in JavaScript is a truth-y value, which allows if (length > 0) .. to be written as if (length) .. and it will work reliably assuming that length is always a number, when present.

Upvotes: 0

fred02138
fred02138

Reputation: 3361

If you want to be explicit about checking that it is an array.

if (response.errors && (response.errors instanceof Array) && response.errors.length > 0)
   deferred.reject(response);
else
   deferred.resolve(response);

(Tested in FF and Chrome).

Upvotes: 0

ajp15243
ajp15243

Reputation: 7952

One way is:

if (response.errors.length) {
    deferred.reject(response);
} else {
    deferred.resolve(response);
}

This is using the fact that 0 is considered falsey in JavaScript, and any other number is considered truthy.

If you're worried about the type of response.errors, you can add response.errors instanceof Array to the if condition:

if (response.errors instanceof Array && response.errors.length) {

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239453

This will make sure that errors is an array and it has items in it.

if (Array.isArray(response.errors) && response.errors.length) {
    deferred.reject(response);
} else {
    deferred.resolve(response);
}

Upvotes: 2

Bergi
Bergi

Reputation: 664385

What about

if (response.errors && response.errors.length > 0)
   deferred.reject(response);
else
    deferred.resolve(response);

No need to catch exceptions from accessing non-existent properties, just test for their existence before…

Upvotes: 0

Related Questions