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);
}
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);
}
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);
}
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) {
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.
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…
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).