DEV Community

Discussion on: 5 Tips to Write Clean Code in JavaScript

Collapse
 
laianbraum profile image
Laian Braum

Hey Simon, nice article! Dev.to recommended it to me and I really enjoyed the read. Very well written and good points raised.

To foment the discussion, I'd like to point out something

  1. Nested if statements and switch cases
  • The good part
    • Switch cases are way more readable than if's statements when we're talking about multiple conditionals.
  • The solution
    • Object literals! They are as readable as switch statements. You can be as creative as you want with them, so you're not forced to break any pattern or standard.

Instead of

switch (dayOfTheWeek)) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
  default: 
    throw new Error("Hey! We have only 7 days in the week");
}
Enter fullscreen mode Exit fullscreen mode

How about

const dayOfTheWeek = {
  0: "Sunday",
  1: "Monday",
  2: "Tuesday",
  3: "Wednesday",
  4: "Thursday",
  5: "Friday",
  6: "Saturday",
};

console.log('day of the week:', dayOfTheWeek[new Date().getDay()]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
simeg profile image
Simon Egersand 🎈

Hi! Thanks!

I totally agree with you. I used a list as an example but objects are definitely better than switch cases when there are many cases!

Thanks for sharing 😌