hussain
hussain

Reputation: 7083

How to check if array is empty using if condition?

respons is coming back empty [] for this.rxInfos but below if condtion never executed any idea what is missing here ?

main.js

if (!Array.isArray(this.rxInfos) && this.rxInfos.length === 0) {
            return this.errorHandler(request, 'no rx found in the cache');
        }

Upvotes: 0

Views: 391

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386578

You could check not an array or if no length.

The first part

!Array.isArray(this.rxInfos)

is true, if the value of this.rxInfos is not an array.

The logical OR || allows to end the check, which is important, if the first operand it truthy. If not, then an array is given and the second part

!this.rxInfos.length

with the length and their logical NOT ! is evaluated and that means, if a length of zero, the last part is true or if the length has another value than zero, the part yields false.

if (!Array.isArray(this.rxInfos) || !this.rxInfos.length) {
    return this.errorHandler(request, 'no rx found in the cache');
}

Upvotes: 2

NaDeR Star
NaDeR Star

Reputation: 655

Just remove first !

 if (this.rxInfos !== undefined && Array.isArray(this.rxInfos) && this.rxInfos.length === 0) { return this.errorHandler(request, 'no rx found in the cache'); }

Upvotes: 0

Related Questions