function declarations cannot be inside an if statement according to ecmascript

152 Views Asked by At

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.

2

There are 2 best solutions below

11
Steven Spungin On

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.

1
Bergi On

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.