'Check two arrays not empty and not undefined

Suppose arr1 is of type number[] | undefined. Normally, to exclude either emptyness and undefined I simply do:

if (arr1)
  // Here arr1 has at least one element

However, suppose that there is also arr2 of type number[] | undefined. I would like to check both for not empty and not undefined (and also make sure that ts doesn't complain). However this behaves wierdly:

if (arr1 && arr2)
  // ???

It looks like arr1 && arr2 is not doing a boolean AND but instead is doing a kind of intersection between the two arrays.

How could I rewrite this simple if condition to achieve what I need?



Solution 1:[1]

if (arr1)
 

Only checks if the array is defined (as !![] returns true, unlike !!'' which returns false)

Therefore arr1 && arr2 will return true when both array are defined, empty or not.

What you want is following :

arr1 && arr1.length && arr2 && arr2.length

Solution 2:[2]

if (arr1?.length && arr2?.lenght) {
    // both arr1 and arr2 contain at least one element
}

arr1?.length returns the length of the array or null if arr1 is null.

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Solution 3:[3]

A user-defined type guard would work:

function isNotEmptyOrUndefined(a: number[] | undefined): a is [number, ...number[]] {
    return Boolean(a && a.length);
}

if (isNotEmptyOrUndefined(arr1) && isNotEmptyOrUndefined(arr2)) {
    // ...
}

docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthieu Riegler
Solution 2 Manuel
Solution 3