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?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ 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

Ad