DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
maxart2501 profile image
Massimo Artizzu

This is messed up and you shouldn't do it, but we can sort-of have pattern matching in JavaScript:

switch (true) {
  case 200 <= status && status < 300: {
    console.log('Success!');
    break;
  }
  case status === 418: {
    console.log("I'm a 🫖");
    break;
  }
  default:
    throw Error('Something went wrong!');
}
Enter fullscreen mode Exit fullscreen mode

The trick here is that the first case that equals the argument of the switch statement is executed. So, since the argument is true, only the first case that have an argument that evaluates to true is executed. Boom!

Also, no. Don't do this. Nobody expects this.

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability.