JavaScript: for while do Loop

By Xah Lee. Date: . Last updated: .

“for” Loop

for (var i=0; i < 9; i++) { console.log(i); }

Note: the variable exist outsite of the loop. If this “for” statement is inside a function, that the variable is local to that function. Else, it's global. 〔►see JavaScript Variable Scope: Function Level vs Block Level

“while” Loop

var x = 0;
while (x !== 5) { console.log(x); x++;} // prints 0 to 4

“do…while” Loop

var x = 0;
do { console.log(x); x++} while (x !== 5) // prints 0 to 4

“continue”, “break”

for (var i=0; i <= 5; i++) {
    if (i===3) {continue;}       // skip 3
    console.log(i);
}                               // prints 0 to 5, but not 3
for (var i=0; i < 5; i++) {
    console.log(i);
    if (i===3) {break;}
}                               // prints 0 to 3

JavaScript Basics

  1. How to Run JavaScript
  2. JavaScript: How to Use Browser's JS Console
  3. JavaScript Tutorial by Example
  4. JavaScript: Data Types
  5. JavaScript: true, false
  6. JavaScript: Operators
  7. JavaScript: Variable
  8. JavaScript: Branch Control: if then else, switch
  9. JavaScript: for while do Loop
  10. JavaScript: Array Basics
  11. JavaScript: Object Basics
  12. JavaScript: RegExp Tutorial
  13. JavaScript: Throw Try Catch Finally
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.