Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

for(;;){
    //...
}

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?

like image 578
ajax333221 Avatar asked Mar 30 '12 03:03

ajax333221


1 Answers

From forMDN

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

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

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.

(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!

like image 70
calebds Avatar answered Sep 28 '22 06:09

calebds