3

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.

Majid M.
  • 4,467
  • 1
  • 11
  • 29
MarkBeras
  • 459
  • 1
  • 3
  • 13
  • 2
    `testArray == []` will always be false. See: [Why doesn't equality check work with arrays](https://stackoverflow.com/q/30820611) and [Why isn't \[1,2,3\] equal to itself in Javascript?](https://stackoverflow.com/q/7314635) Moreover, if you get `testArray.includes is underfined` then you don't have an empty array, you have some sort of value that is not an array. Likely an object. – VLAZ Jul 19 '21 at 07:03

3 Answers3

7

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
}
Majid M.
  • 4,467
  • 1
  • 11
  • 29
0
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
NotoriousPyro
  • 526
  • 3
  • 16
-1

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.