I want to check the response.data.totalRows
is empty.
if (response!=undefined
&& response.data!=undefined
&& response.data.totalRows!=undefined) {
alert(response.data.totalRows);
}
Can simplify the code?
UPDATE: it seems that there is no simple method like isEmpty(response.data.totalRows)
.
Yea, you can simply do this:
if (response && response.data && response.data.totalRows) {
alert(response.data.totalRows);
}
In JavaScript, a object is cast to a truthy
value, when used in a if
. This means you can just "dump" the variable in a if
or any other boolean statement, as a check to see whether or not it exists. this blog post has some more information about it.
Please note that this will not alert anything if totalRows
equals 0
(since 0
is considered a falsy
value.) If you also want to alert if it's 0
, use this:
if (response && response.data &&
(response.data.totalRows || response.data.totalRows === 0)) {
alert(response.data.totalRows);
}
Or:
if (response && response.data && response.data.totalRows !== undefined) {
alert(response.data.totalRows);
}