Why does this 'for(;;)' loops?

What in the world is making the second parameter return true?

WARNING: it will loop infinitely and might crash your browser


I was totally expecting not to loop at all...

But it is running, and that makes it worse since it can only be running if something evaluated to true, or am I missing something?



From forMDN

for ([initialization]; [condition]; [final-expression])

[Initialization] and [final-expression] are intuitively not required, reducing the construct to a simple while loop. But the relevant part is:

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.

(emphasis mine)

This appears to be a totally arbitrary JS language design decision. If it were my language I would probably throw a syntax error.

On a playful side note, for(;;){} is equivalent to while(true){}, and happens to be 4 characters shorter. I wonder if minifiers leverage this!


Because the lack of a condition will always evaluate to true.


There's nothing “making the second parameter return true”. There is no second parameter. Section 12.6.3 of the ECMAScript Language Specification (ECMA-262 5th Edition) says this:

a. If the first Expression is present, then

i. Let testExprRef be the result of evaluating the first Expression.

ii. If GetValue(testExprRef) is false, return (normal, V, empty).

The “first Expression” it's referring to is the optional expression between the semicolons of the for statement. If it's present, the program performs steps (i) and (ii) quoted above. If the expression is not present, the program simply doesn't perform steps (i) and (ii) of the for statement algorithm.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.