Home > database >  If I call a function in the head section of JavaScript for-of loop, is it guarantied to be called on
If I call a function in the head section of JavaScript for-of loop, is it guarantied to be called on

Time:06-04

I have tried the code below in Firefox and Chrome:

function test() {
    console.log("***")
    return [1,2,3]
}

for (const t of test()) {
    console.log(t)
}

The test function was called only once. Is it the standard behavior for this kind of loop? Is it like the initialization part of for ([initialization]; [condition]; [final-expression]) loop? I didn't find the explanation on MDN and I didn't understand much from ECMA standard.

CodePudding user response:

The ECMAScript specification splits the runtime semantics of the for..in and for..of construct into two parts:

ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement

  1. Let keyResult be ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate).
  2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, iterate, assignment, labelSet).

So we first have the "head" evaluation (involving the "AssignmentExpression" at the right of of), and after that, the "body" evaluation, which uses the keyResult (not the AssignmentExpression).

The "head" evaluation involves the actual evaluation in step 3 of that procedure:

  1. Let exprRef be the result of evaluating expr.

The "body" evaluation involves the actual iteration in step 6:

  1. Repeat
  • Related