switch / case as expression

Hello!

Sometimes I’m rubbing my hands in enjoyment over a nice return statement I’m writing in a React component, only to realise that I need to write a function for the sole purpose of using a switch/case block in the expression following return. What if, just like throw, switch/case could be an expression instead?

One possible implementation would be to wrap switch inside an immediately invoked function expression, i.e., an implicit iife, if you will:

// input
const fn = () => {
  return switch (a) {
    case 1:
      return 'hello'

    case 2:
      return 'world'
  }
}
// output
const fn = () => {
  return (() => {
    switch (a) {
      case 1:
        return 'hello'

      case 2:
        return 'world'
    }
  })()
}

Why this change, if we can use an IIFE instead? Because I think they’re a bit ugly, syntax-wise, and perhaps confusing to the uninitiated; whereas the new syntax looks more orderly and is more convenient to use inside expressions.

Thanks in advance for your feedback!

I think this is covered by Do Expressions.

I think that the syntax you propose would be possible, as switch is currently a syntax error inside expression context. However I'm not quite sure that return should be used to determine the expression the switch expression would evaluate to, as (a) it would make it impossible to return regularily, and (b) it would make it hard to determine what return returns to.

Yup, specifically

const x = do {
  switch (a) {
    case 1: 'hello'; break;
    case 2: 'world'; break;
  }
}

You can try it out in the Browser console: paste this, it outputs 5:

switch(true) {
    case true: 5; break;
    case false: 6; break;
}

Do expressions use the same logic.

Also: https://github.com/tc39/proposal-pattern-matching

Your initial fn might look like this using that proposal:

const fn = () =>
    case (a) {
        when 1 -> 'hello',
        when 2 -> 'world',
    }
2 Likes

Java has recently added a switch expression which solves many of the common issues with switch statements. I suggest we look at using it as a model. Benefits include an enforced default, not needing to worry about break statements and fallthrough, evaluating as an expressoin, and each branch being its own block scope.

All of these are already part of the pattern matching proposal.

1 Like