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.

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Build modern and responsive webpages

Responsive Typography

Build modern and responsive webpages Try Front-end

Responsive web design helps your site maintain its design integrity on a variety of screen sizes, but how does it affect your typography? With this practical book, graphic designers, web designers, and front-end developers alike will learn the nuts and bolts of how to get the best appearance from type without sacrificing performance on any device.

$ Check price
24.9924.99Amazon 4.5 logo(3+ reviews)

More Front-end resources