Home > OS >  Function returns undefined and lacks ending return statement
Function returns undefined and lacks ending return statement

Time:10-21

i want to filter a object based on a property which is in array of objects. For that i have written the filter condition separately.

This is where i call my filter condition

.filter((service) => {
          filterOverlappedServices(service);
        })

And this is my filter condition

const filterOverlappedServices = (service: Item): boolean => {
    if (bookings) {
      bookings.forEach((booking) => {
        return moment(service?.duration?.start).isBetween(
          booking.data[0]?.duration?.start,
          booking.data[0]?.duration?.end,
          'minute',
        );
      });
    } else {
      return true;
    }
  };

What i have done here is check if the given date string (isostring) has a time inbetween the other 2 start and end times.

However this always return undefined and also shows a typescript error as

Function lacks ending return statement and return type does not include 'undefined'.

But isnt my function return either true or false based on my implementation? From where does it return a undefined?

CodePudding user response:

You're getting the error because your "filter function" is not returning anything. Try changing

.filter((service) => {
          filterOverlappedServices(service);
        })

to

.filter((service) => {
          return filterOverlappedServices(service);
        })

or even

.filter(filterOverlappedServices)

Also, the return in the forEach doesn't return from filterOverlappedServices. Actually, that return doesn't do much at all. forEach always returns undefined and so, it doesn't make sense for its callback to have a return value. You're either looking for map or something else entirely.

CodePudding user response:

Because you are using .forEach with a callback function, the return doesn't do anything in the outer function, only in the callback.

In my experience, .forEach rarely gives me something I want, so I mostly always change it to a for (const booking of bookings) type of loop. In there, you can return to the outer function.

Btw: If you return in the for loop, only the first one will actually return, the others will be skipped.

CodePudding user response:

forEach is a remnant of ES5 that has several limitations due to its use of callback function. Return value is ignored and there's no straightforward way to break a loop.

Another problem is that filter ignores return value.

In order to check that some array elements conform to a condition, a respective method can be used:

.filter((service: Item) => {
    return !bookings ? true : bookings.some((booking) => {
        return moment...;
    });
});
  • Related