DEV Community

Discussion on: Constants In JavaScript Switch

Collapse
 
kosich profile image
Kostia Palchyk

I think, you can wrap case body in {…}, e.g:

function demo () {
  const demo = {
    first: 1
  };

  switch (demo.first) {
    case 1: {
      let result = 1;
      return result;
    }
    case 2: {
      let result = 2;
      return result;
    }
    case 3: {
      let result = 3;
      return result;
    }
    default:
      return demo.first;
  }
}
Enter fullscreen mode Exit fullscreen mode

--

Also, there's a hack that always blows my mind:

(not for production imho, but interesting)

switch (true) {
  case (demo.first == 1) {}
  case (demo.first == 2) {}
  case (callSomeFunction(demo.first)) {}
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rfornal profile image
bob.ts

Interesting.

  • I'll add the first case to my notes.
  • The second case is one I love to use. I think it actually makes it more readable.
Collapse
 
rfornal profile image
bob.ts

Added the pattern to the main article!