I'm experiencing some weird behavior with a JavaScript function which I think may be a syntax issue/misunderstanding on my part as to how JavaScript "returns" function. The code in question looks like this:
const preventOverlapInSchedule = (start, end) => {
duties.forEach(function (duty) {
if (
(start >= duty.start && start <= duty.end) ||
(end >= duty.start && end <= duty.end) ||
(start <= duty.start && end >= duty.end)
) {
console.log("false");
return false;
}
});
console.log("true");
return true;
};
This function is then used to prevent a scheduling conflict. However both the console log statements above are printing. Coming from Java, traditionally I would expect that the second the if condition evaluates to true, the function should return false, indicating that there is a scheduling conflict, i.e. the start time or end time of the new event has either partial or full overlap with another event already recorded, and then the function should immediately exit.
However the behavior I'm noticing is that regardless of the scheduling of the event, both of the console logs above print to the screen, which would indicate that returning false within my if statement does not cause the JavaScript function to exit immediately. Can anyone tell me why this is happening?
forEachcallback so the outer function always returns true. Use afor (...)loop. Better yet, usereturn duties.some(e => /* predicate */). Lastly, the function breaks idempotency/scoping rules by not takingdutiesas a parameter.forEachdoes not return from the outer function.