开发者

Empty for loop - for(;;)

I was exploring the Google Closure Compiler, and one thing I noticed was that it converts while(true) into for(;;).

Both do hang the browser, but why does the empty for loop not break out of itself immediately? The second part of it is empty, and there开发者_C百科fore falsy. Isn't it true that when the second part is falsy, the for loop stops and execution continues with code which comes after the for loop?

Could someone perhaps give an explanation for this?


No, it is not true.

See: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for

condition

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

I should perhaps give a link to ECMAScript reference, but I'm pretty sure it states more or less same thing.


From the ECMAScript language specification:

IterationStatement : for (ExpressionNoIn_opt ; Expression_opt ; Expression_opt) Statement

If the first Expression is present, then

  1. Let testExprRef be the result of evaluating the first Expression.
  2. If GetValue(testExprRef) is false, return (normal, V, empty).

Since the first expression (the second argument to for) is not present, this section is never run, so the for loop does not exit.


An empty middle part should be interpreted as true, so it's not falsy. It has the same semantics in C and other languages with that kind of loop (like C#, Java and so on). It would be a real trap to have changed it for JavaScript.


There is evaluation algorothm of for loop in Standard ECMA-262 script that says there are only two situations in which loop will end:

  1. break statement
  2. value of middle statement equal to false, but only if this statement is present, so it doesnt have to be necessary valuated as true (probably in mozilla js engine it is).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜