Skip to content

Clause separators #337

@gkz

Description

@gkz

Currently, the clause separator specified in this proposal is a semicolon:

const e = match (x) {
  1: f();
  2: g();
};

From what I can see, the history of using the semicolon comes from this GitHub issue, where the point made was that having no clause separator syntax (just a prefix when, now removed) would cause parsing issues. It was suggested that something like a semicolon could solve the issue. However, semicolons are not currently used as punctuation in any other expressions (other than nested within function or class expressions). They are used and associated with the syntax for statements in JavaScript instead.

Before we get into possible solutions, let’s look at prior art for match expression clause separators in other languages:

  • Comma , suffix: Dart, Rust, C#
  • case prefix: Swift, Scala
  • case prefix and semicolon ; suffix: Java
  • Bar | prefix: OCaml, F#
  • Nothing (newline): Haskell, Kotlin

Could we use a comma instead of a semicolon in JavaScript? Yes. The only difference would be that we would parse the body of each clause as an AssignmentExpression (requiring sequence expressions to be surrounded by parenthesis). This is what JavaScript uses in call expressions, array literals, and object literals.

Object literals provide a mapping from keys to expressions:

const obj = {
  1: f(),
  2: g(),
};

In match expressions, we provide a mapping from patterns to expressions. This is not completely dissimilar.

What would using commas for match expressions look like?

const e = match (x) {
  1: f(),
  2: g(),
};

I believe looking at the prior art of other languages, and the prior art within JavaScript itself, it is worth considering whether using commas , as clause separators would be a better fit than semicolons ;.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions