I wrote a little code snippet to check, weather a date lies in holidays or if it is a normal working day. When I use the function with a date in holidays the function seems to return true. When i check, if the function with the date is true, it seems that no true value is returned.
Exspected output is:
Holiday!
Holiday
Real output is:
Holiday!
Working Day
What am I missing? Thanks for any help.
I tried to debug my code. The if-Statement in the function gets true, so i guessed, that the function itself would be true.
//list of holidays
const ferien = {
//Sommerferien: ["2022-07-25", "2022-09-02"],
//Herbstferien: ["2022-10-17", "2022-10-31"],
//Weihnachtsferien: ["2022-12-23", "2023-01-02"],
//Osterferien: ["2023-04-03", "2023-04-06"],
Pfingsferien: ["2023-05-30", "2023-06-07"],
};
//function to check, weather a date is in holiday or not
const getFerien2 = (date) => {
//should run through all keys from ferien-Object
Object.keys(ferien).forEach((element) => {
//Test if timestamp of date lies between starting- and enddate of holiday "Pfingsferien"
if (
Date.parse(ferien[element][0]) <= Date.parse(date) &&
Date.parse(date) <= Date.parse(ferien[element][1])
) {
console.log("Holiday!");
return true;
} else {
return false;
}
});
};
//Test for a specific date
if (getFerien2("2023-05-31") === true) {
console.log("Holiday");
} else {
console.log("Working Day");
}
You're attempting to return from inside the loop, so the function never actually returns true
. Use a Boolean value to track whether a holiday is found, and return that.
Other notes:
true
. Just check it for truthiness.//list of holidays
const ferien = {
//Sommerferien: ["2022-07-25", "2022-09-02"],
//Herbstferien: ["2022-10-17", "2022-10-31"],
//Weihnachtsferien: ["2022-12-23", "2023-01-02"],
//Osterferien: ["2023-04-03", "2023-04-06"],
Pfingsferien: ["2023-05-30", "2023-06-07"],
};
// function to check, weather a date is in holiday or not
const getFerien2 = date => {
let holidayFound = false;
// Run through all keys from ferien-Object
Object.keys(ferien).forEach(element => {
// Test if timestamp of date lies between starting- and enddate of holiday "Pfingsferien"
if (
Date.parse(date) >= Date.parse(ferien[element][0]) &&
Date.parse(date) <= Date.parse(ferien[element][1])
) {
holidayFound = true;
}
});
return holidayFound;
};
// Test for a specific date
if (getFerien2("2023-05-31")) {
console.log("Holiday");
} else {
console.log("Working Day");
}