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

158
Visualizações
function declarations cannot be inside an if statement according to ecmascript

how is it even possible to declare a function inside an IfStatement ? because according to the ecmascript spec only a Statement can be there.

if ( Expression ) Statement

if ( Expression ) Statement else Statement

and FunctionDeclaration isn't a Statement but it's a Declaration

so maybe i've missed something or maybe Browsers cannot implement such thing nowadays because it may ruin websites that use function declarations inside an if statement.

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

0

It is not possible to put a function declaration in an if statement. Try

if (true) function example() {}

in strict mode - you'll get a SyntaxError. To declare a function inside a conditional branch, you must put it inside a Block, which is a Statement (through BlockStatement) and can contain Declarations (in a StatementList).

Maybe Browsers cannot implement such thing nowadays because it may ruin websites that use function declarations inside an if statement.

Yes indeed. For web legacy compatibility, function declarations in if statements are allowed in sloppy mode. Don't write code like that, but browser are allowed to treat it as valid.

about 4 years ago · Juan Pablo Isaza Relatório

0

From the spec:

At the top level of a function or script, inner function declarations are treated like var declarations.

The chain goes like this.

Statement => BlockStatement => StatementList => StatementListItem => Declaration => VarDeclaration

It's all right here, statement list item

https://tc39.es/ecma262/#prod-StatementListItem

Prior to ECMAScript 2015, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement's StatementList. However, support for that form of FunctionDeclaration was an allowable extension and most browser-hosted ECMAScript implementations permitted them.

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