DEV Community

Discussion on: JavaScript 'for loops' for Newbies

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

It's worth pointing out that the expressions can be omitted. For example, you could make a for loop run for 5 seconds, then end:

const startTime = performance.now()
for (;performance.now()-startTime < 5000;) {
  console.log('Running for 5 seconds')
}
Enter fullscreen mode Exit fullscreen mode

Or, run until some external process is complete:

for (;isExternalProcessComplete();) {
  console.log("Process is still running...")
}
Enter fullscreen mode Exit fullscreen mode

Or, run forever (probably not advisable):

for (;;) console.log("Don't do this")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lindsfonnes profile image
Lindsey Fonnesbeck

Interesting, thanks for that! Learning something new every day!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

It is also possible to omit the statement(s) to run, and do all processing purely in the expressions. If you do this however, you must follow the closing bracket of the loop conditions with a semicolon (one of the few cases in JS where the semicolon is mandatory)