0

I'm beginning to understand JavaScript now but I try to understand how I can shorten a if else statement like this.

let today = prompt('Enter day').toLowerCase();

if(today === 'monday' || today === 'tuesday' || today === 'wednesday' || today === 'friday') {
    console.log(`${today.replace(/^\w/, (c) => c.toUpperCase())} is a work day.`);
} else if(today === 'saturday' || today === 'sunday') {
    console.log(`${today.replace(/^\w/, (c) => c.toUpperCase())} is weekend day.`);
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Herman93
  • 11
  • 2
  • you can [switch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) your approach this way. – yqlim Sep 05 '21 at 19:31
  • 1
    For readability, you can define a function `isWeekday()` - this will make your posted logic just a simple `if (isWeekday()) { /* code */ } else { /* code */ }`. You can use a `switch` statement as well, but since you're switching on `string`s, you won't get any real performance benefit from the `switch` at all. The function approach is nicer, in my opinion. Note, this question is likely to generate an opinion-based set of answers... – CoolBots Sep 05 '21 at 19:35
  • Does this answer your question? [Check variable equality against a list of values](https://stackoverflow.com/questions/4728144/check-variable-equality-against-a-list-of-values) – Heretic Monkey Sep 05 '21 at 19:38
  • 2
    That's almost exactly what the w3schools example is for the use of a switch statement. See the first example: https://www.w3schools.com/js/js_switch.asp Swap out the switch for your prompt and make each case the `today === etc` – srWebDev Sep 05 '21 at 19:39
  • @srWebDev yep, except in that example they are switching on an integer value (contiguous, too!), therefore actually benefitting from the switch. Good example though! – CoolBots Sep 05 '21 at 19:41

5 Answers5

2

My approach

<!DOCTYPE html>
<html>
    <body>
        <script type="text/javascript">
            const today = prompt("Enter day");
            const days = {weekdays: ["monday", "tuesday", "wednesday", "thursday", "friday"], weekends: ["saturday", "sunday"]}
            days.weekdays.includes(today) ? document.write(`${today.replace(/^\w/, (c) => c.toUpperCase())} is a work day.`) : (days.weekends.includes(today) ? document.write(`${today.replace(/^\w/, (c) => c.toUpperCase())} is weekend day.`) : console.log(`${today} is not a day`));
        </script>
    </body>
</html>
Lakshaya U.
  • 1,089
  • 1
  • 5
  • 21
2

let today = prompt('Enter day').toLowerCase();

let weekdays = ['monday', 'tuesday', 'wednesday', 'friday']
let weekends = ['saturday', 'sunday']

let dayString = weekdays.includes(today) ?  ` is a work day.` : weekends.includes(today) ? ` is weekend day.`: '';
let finalString = `${today.replace(/^\w/, (c) => c.toUpperCase())}` + dayString;

console.log(finalString);
1

Assuming here that we don't have much info from you, and this kind of snippets could have some other issues before being considered "solid"

Just for the sake of the question... I'd make the snippet shorter like this:

let workOrWeekendDay =
today === "saturday" || today === "sunday" ? "weekend" : "a work";

console.log(
`${today.replace(/^\w/, (c) => c.toUpperCase())} is ${workOrWeekendDay} day.`
);
koalaok
  • 5,075
  • 11
  • 47
  • 91
0

I would use regular expressions

if(/monday|tuesday|wednesday|thursday|friday/.test(today))

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
0

Check out the includes() method.

let today = prompt('Enter day').toLowerCase();

if('monday tuesday wednesday friday'.split(' ').includes(today)) {
    console.log(`${today.replace(/^\w/, (c) => c.toUpperCase())} is a work day.`);
} else if(['saturday', 'sunday'].includes(today)) {
    console.log(`${today.replace(/^\w/, (c) => c.toUpperCase())} is weekend day.`);
}

In the first use above, we also employ split() in order to condense the list a little bit. This only really helps with particularly long lists. And there is a performance hit the longer the string is, so this is just to give you an idea of some options that might work for you if it is a rarely used piece of code.

In the weekend case, an explicit list is defined without split(). I find this approach better for small lists. Predefining the list may help with readability and anywhere that the comparison is used multiple times. Ex:

const weekend = ['saturday', 'sunday'];
if (weekend.includes(today)) ...
Kenny
  • 125
  • 6