Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Is it valid syntax in ECMAScript to surround each case in a switch / case statement with curly braces?

I'm never entirely comfortable with formatting switch/case statements in JavaScript. Given the following:

switch (myVariable) {

  case ('a'):
  console.log('apple');
  break;

  case ('b'):
  console.log('banana');
  break;

  case ('c'):
  console.log('cherry');
  break;

  default:
  console.log('pineapple);
}

I feel that the lines after the case declaration ought to be indented.

But if they were indented, there would then be a peculiar-looking two-column gap between the last line of the last case and the closing curly brace of the switch block.

It has just occurred to me that I might surround the code of each case within their own curly braces.

I suspected this might be invalid, but my browser is happy with it, Prettier is happy with it and, surprisingly, even JSHint is content with this formatting.

Here is an example of what I'm describing:

switch (myVariable) {

  case ('a'): {
    console.log('apple');
    break;
  }

  case ('b'): {
    console.log('banana');
    break;
  }

  case ('c'): {
    console.log('cherry');
    break;
  }

  default: {
    console.log('pineapple);
  }
}

This formatting enables code indentation without introducing the two-column gap.

But surely this isn't valid ECMAScript syntax, is it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the syntax, a single "case" is called a CaseClause. A CaseClause is componsed of:

case Expression: StatementList

A StatementList is composed of a StatementListItem.

A StatementListItem is either a statement or declaration.

A statement may be a BlockStatement.

A block statement is a plain block - which is a block which contains a StatementList:

{ StatementList }

So yes, it's valid syntax.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda