Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!