JavaScript: for while do Loop

By Xah Lee. Date: . Last updated: .

“for” Loop

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

“while” Loop

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

“do…while” Loop

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

“continue”, “break”

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

for-in Loop vs for-of Loop

for-in Loop

This is for going thru a object's properties, including parent object's properties. You need to understand properties and inheritance first. See for-in Loop

for-of Loop

This is for going thru iterable objects. You need to understand iterable object first. See for-of Loop

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc