5

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.

1

3 Answers 3

10

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

if (!testArray || testArray.length == 0 || testArray.includes(value)) {
    // do something
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it and it doesn't work too – testArray. length is underfined error
Could you share your testArray's items? I updated my code. Please try it again.
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

Comments

-2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.