Search code examples
javascriptcontext-free-grammarecmascript-2020

can someone explain me why the grammar of for, while, do-while statement define that the condition part within the header is an "Expression"


Can someone explain to me why the grammar of for, while, do-while statement's define that the condition part within the header is an "Expression" and can someone explain me what the below thing means

Expression[In, Yield, Await] :
      AssignmentExpression[?In, ?Yield, ?Await]
      Expression[?In, ?Yield, ?Await] , AssignmentExpression[?In, ?Yield, ?Await]

As you see there is no Literal at the right hand side after the non-terminal Expression[In, Yield, Await] : but still it's possible to write literals within the header of a for-statement, while-statement, do-while statement

for (var i = 0; null; i ++) {
             /* ^^^^ */
             /* null */   
}

while (null) {
    /* ^^^^ */
    /* null */
}

do {} while (null) ; 
          /* ^^^^ */
          /* null */

And it's also possible to write function expressions within the header of those statement's even though FunctionExpression is not present in the right hand side of non-terminal Expression[In, Yield, Await] :

for (var i = 0; function () {}; i ++) ;
             /* ^^^^^^^^^^^^^^ */
             /*  functionExpr  */

while (function () {}) ;
    /* ^^^^^^^^^^^^^^ */
    /*  functionExpr  */
    
do ; while (function () {}) ;
         /* ^^^^^^^^^^^^^^ */
         /*  functionExpr  */
         


Solution

  • Took me some search in the documentation, but what i found is (summarized):

    Expression: 
        AssignmentExpression
    

    Then, among others:

    AssignmentExpression: 
        LeftHandSideExpression
    

    So we can go deeply in the nesting:

    LeftHandSideExpression: 
        NewExpression
    
    NewExpression: 
        MemberExpression
    
    MemberExpression: 
        PrimaryExpression
    

    And find out that PrimaryExpression contains many other items, but also Literal and FunctionExpression:

    PrimaryExpression[Yield, Await]:
         this
         IdentifierReference[?Yield, ?Await]
         Literal
         ArrayLiteral[?Yield, ?Await]
         ObjectLiteral[?Yield, ?Await]
         FunctionExpression
         ClassExpression[?Yield, ?Await]
         GeneratorExpression
         AsyncFunctionExpression
         AsyncGeneratorExpression
         RegularExpressionLiteral
         TemplateLiteral[?Yield, ?Await, ~Tagged]
         CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
    

    I hope my answer it's enough clear and clarifies your doubts