Check if array is empty or includes the value, typescript

Viewed 6598

I check if array includes the value this way:

testArray.includes(value)

I need to do the same action if array is empty OR it includes the value. So I have this condition:

if (testArray == [] || testArray.includes(value)) {
    // do something
}

But typescript is trying to execute the second part of this condition even if testArray == []. So I receive an error testArray.includes is underfined.

I understand that I can fix it this way:

if (testArray == []) {
    // do something
} else if (testArray.includes(value)) {
    // do the same thing
}

But it doesn't look nice. Is there a way to put it in one if?

testArray is an openapi query parameter, if it's important.

3 Answers

Acctually, array is a reference type. When you would like to check it with [ ], they aren't equal. They're totally different, it's better to check this condition with length. So based on your code you should do something like this :

if (!testArray || testArray.length == 0 || testArray.includes(value)) {
    // do something
}
function isValueInArrayOrEmpty(updated) {
    console.log(Boolean(updated instanceof Array && (updated.length == 0 || (updated.length > 0 && updated.includes(value)))));
}
let value = "hello";
let updated = [];
isValueInArrayOrEmpty(updated);
let updated2 = "hello";
isValueInArrayOrEmpty(updated2);
let updated3 = Object;
isValueInArrayOrEmpty(updated3);
let updated4 = [Object];
isValueInArrayOrEmpty(updated4);
let updated5 = ["hello"];
isValueInArrayOrEmpty(updated5);
let updated6 = ["not hello"];
isValueInArrayOrEmpty(updated6);

VM815:2 true
VM815:2 false
VM815:2 false
VM815:2 false
VM815:2 true
VM815:2 false

if (testArray == [] || testArray.includes(value)) { // do something }

In case of OR operator if the first condition is true it will skip rest all conditions. With that said your first condition testArray == [] is false , hence its executing the second part of condition. Probably your array is not empty array its having undefined value as it might not be initialized. Hence its throwing error.

Related