04. Loops

Loops are used to repeat a block of statements a set number of times.

for loops

When using a for loop, you instantiate a counter variable (initialization), set a condition for the loop to run until (condition), then set some increment/decrement operator for the counter (update).

for (var i = 0; i < 10; i++) {
  // code statement blocks here to run 10 times.
} 

Here is a list of the steps per a for loop:

  1. Initialize variable i to 0.
  2. Check if i is less than 10. If not, exit the loop.
  3. Run the code statements.
  4. Increment i.
  5. Go back to step 2 and repeat.

while loops

while loops are similar, but the only parameter needed is the condition. Before JavaScript runs the code block within this loop, it makes sure that the condition evaluates to true.

while (i < 10) {
  // Execute some commands
  i += 2; // update your counter, otherwise infinite loop.
}

do-while loops

To ensure that your code runs at least once, you may use a do-while loop. The do-while loop first executes, then checks your conditional statement.

do {
  // Execute a command block
  x += 1;
} while (x < 10);

break and continue

Two extremely helpful one-word statements used exclusively in loops are break and continue. The former exits out of the loop, while the latter pushes the JavaScript interpreter back up to the conditional statement.

Build modern and responsive webpages

HTML & CSS

Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad