I am playing around with the JavaScript IF/ELSE to understand better how it works. As an exercise I took the following working hours of a shop:
- 6AM to 6PM = Open
- 6PM to 6AM = Closed
then I created a function that returns the word 'Open' or 'Closed' based on the 2 values "time" and "period".
function shopHours(time,period) {
if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 6 && period === 'AM') {
return 'Open';
} else if (time === 7 && period === 'AM') {
return 'Open';
} else if (time === 8 && period === 'AM') {
return 'Open';
} else if (time === 9 && period === 'AM') {
return 'Open';
} else if (time === 10 && period === 'AM') {
return 'Open';
} else if (time === 11 && period === 'AM') {
return 'Open';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else if (time === 1 && period === 'PM') {
return 'Open';
} else if (time === 2 && period === 'PM') {
return 'Open';
} else if (time === 3 && period === 'PM') {
return 'Open';
} else if (time === 4 && period === 'PM') {
return 'Open';
} else if (time === 5 && period === 'PM') {
return 'Open';
} else {
return 'Closed';}
}
Everything works fine. However, I would like to be able to shorten the code as it looks too confusing.
I then tried the following:
function shopHours(time,period) {
if(time <= 6 && period === 'AM') {
return 'Closed';
} else if (time >= 6 && period === 'PM') {
return 'Closed';
} else if (time === 12 && period === 'PM') {
return 'Open';
} else {
return 'Open';}
}
The second code works fine too and is much shorter however there is a problem that I am not sure how to solve. When the time and period are set to 12 and PM, the result should be 'closed' but I am not sure how to implement this.
I have tried to add the following code but it seems that would not solve this problem.
else if (time === 12 && period === 'AM') {
return 'Closed';
}
I will be very grateful to anyone that will spend a bit of his time to take a look at this question.
Thank you!
elsekeyword is not needed. You can just useif